How to use Enum with Default Values In Mongoose
We can specify a default value for a field with enum and ensuring that it always has a valid initial value.
const userSchema = new mongoose.Schema({
role: {
type: String,
enum: ['user', 'admin', 'moderator'],
default: 'user' // Default value for the 'role' field if not specified during document creation
}
});
Explanation: This Mongoose schema defines a role
field with a type of String and an enum specifying that the field can only have the values ‘user’, ‘admin’, or ‘moderator’. Additionally it sets a default value of ‘user’ for the role
field if no value is provided during document creatio
How to Create and Use Enum in Mongoose
Enums in Mongoose play an important role in defining fields that should only accept a limited number of predefined values. They significantly enhance code readability and maintainability by clearly indicating the possible values for a field.
In this article, We will explore the concept of enums in Mongoose and focus on how they can be created and utilized within Mongoose schemas.