![]() |
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
Creating Enum in Mongoose SchemasTo 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'); 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 MongooseWhen 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 Explanation: In the above code we creates a Mongoose model named Using Enum with Default ValuesWe 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({ Explanation: This Mongoose schema defines a Advanced Usage of EnumUsing Enum with NumbersEnum can also be used with numeric values instead of strings. This is particularly useful when dealing with numerical options. const productSchema = new mongoose.Schema({ Explanation: In this above Mongoose schema defines a Dynamic Enum ValuesWe can dynamically generate enum values based on certain conditions using a function. const validRoles = ['user', 'admin', 'moderator']; Explanation: This Mongoose schema defines a ConclusionIn 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. |
Reffered: https://www.geeksforgeeks.org
Databases |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |