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.

Similar Reads

Understanding Enum in Mongoose

The enums here are essentially String objects. Enums in Mongoose are particularly useful for fields that should only accept a limited number of predefined values. They enhance the readability and maintainability of the code by clearly indicating the possible values for a field. Enums can be used for fields such as user roles, status codes or any other field where a limited set of options is applicable. When defining an enum in Mongoose we specify the allowed values as an array within the schema definition. Enums provide a way to document and apply the expected values for a field making the code more self-explanatory....

Creating Enum in Mongoose Schemas

To use enum in Mongoose, we need to define it within the schema definition for a specific field. Here’s how we can define enum in a Mongoose schema:...

Enum Validation in Mongoose

When a document is created or updated, Mongoose automatically validates the field against the defined enum values. If an invalid value is provided, Mongoose will throw a validation error....

Using Enum with Default Values

We can specify a default value for a field with enum and ensuring that it always has a valid initial value....

Advanced Usage of Enum

Using Enum with Numbers...

Conclusion

In conclusion, enums in Mongoose provide a powerful mechanism for defining fields with predefined, restricted values. By using enums, developers can ensure data consistency and integrity, as well as enhance the readability and maintainability of their code. Whether defining user roles, status codes, or any other field with limited options, enums offer a clear and concise way to specify allowed values....