How to Create and Use Enum in Mongoose
Last Updated :
09 Apr, 2024
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.
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:
const mongoose = require('mongoose');
// Define a schema for a user
const userSchema = new mongoose.Schema({
role: {
type: String,
enum: ['user', 'admin', 'moderator'] // Enum defining allowed values for the 'role' field
}
});
Explanation: This Mongoose schema defines a user with a 'role' field that can only have values 'user', 'admin', or 'moderator'. The enum ensures that the 'role' field is restricted to these predefined values, enhancing data consistency and integrity.
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.
// Create a model based on the user schema
const User = mongoose.model('User', userSchema);
// Attempt to save a user with an invalid role
const newUser = new User({ role: 'superuser' }); // 'superuser' is not a valid role
newUser.save()
.then(() => console.log('User saved successfully'))
.catch(err => console.error('Error saving user:', err)); // Validation error will be caught here
Explanation: In the above code we creates a Mongoose model named User
based on the userSchema
schema. It then attempts to save a new user with the role 'superuser' which is not a valid role according to the schema's enum. As a result, a validation error will be caught and logged.
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.
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
Advanced Usage of Enum
Using Enum with Numbers
Enum can also be used with numeric values instead of strings. This is particularly useful when dealing with numerical options.
const productSchema = new mongoose.Schema({
status: {
type: Number,
enum: [0, 1, 2], // 0: Inactive, 1: Active, 2: Suspended
default: 0
}
});
Explanation: In this above Mongoose schema defines a status
field with a type of Number and an enum specifying that the field can only have the values 0, 1, or 2. These values correspond to the status of a product where 0 represents 'Inactive', 1 represents 'Active' and 2 represents 'Suspended'. It also sets a default value of 0 for the status
field if no value is provided during document creation.
Dynamic Enum Values
We can dynamically generate enum values based on certain conditions using a function.
const validRoles = ['user', 'admin', 'moderator'];
const userSchema = new mongoose.Schema({
role: {
type: String,
enum: validRoles
}
});
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', which are defined in the validRoles
array. This approach allows for dynamic enum values based on the contents of the validRoles
array.
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.
Similar Reads
How to create an id using mongoose in Javascript? Mongoose is a powerful tool that simplifies MongoDB operations by providing a structured way to define schemas and models. With Mongoose, developers can define relationships between data, apply validation rules, and create reusable query logic. In this article, We will learn about Mongoose, Defining
5 min read
How to Create and Validate JSON Schema in MongoDB? JSON Schema validation in MongoDB allows you to enforce the structure of documents in a collection. This ensures data integrity by validating documents against defined schemas before they are inserted or updated. In this article, we will cover how to create and validate JSON Schema in MongoDB using
5 min read
How to Register and Call a Schema in Mongoose? Mongoose is a powerful Object Data Modeling (ODM) library for MongoDB and Node.js. It provides a straightforward and schema-based solution to model our application data. Understanding how to properly define and work with Mongoose schemas is essential for efficient MongoDB management and data interac
5 min read
How to Delete a Field From a Document in Mongoose? Databases are an essential component of web development. They are used for storing and managing data. MongoDB is a widely used NoSQL database. A Mongoose is a tool designed to simplify interactions with MongoDB databases in Node.js applications, making it an elegant MongoDB object modeling solution.
5 min read
Mongoose Model.create() API In Node.js applications, Mongoose provides an effective way to interact with MongoDB, allowing developers to define models and schemas to store and retrieve data. One of the essential methods provided by Mongoose is Model.create(), which is used to create one or more documents in a MongoDB collectio
5 min read