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.
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.