Open In App

How to Create and Use Enum in Mongoose

Last Updated : 09 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads