How to Create and Use Enum in Mongoose
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.
Mongoose is a powerful ODM (Object Data Modeling) library for MongoDB and Node.js, providing a straightforward schema-based solution to model application data. One of the common requirements when modeling data is the need to specify certain fields to have one of a select set of values. Enumerations (enums) provide an elegant way to achieve this in Mongoose. This article will delve into how to create and use enums with Mongoose, complete with technical explanations and practical examples.
Setting Up Mongoose
To begin, ensure you have Mongoose installed in your project. If not, you can install it via npm:
Next, connect to your MongoDB database:
Creating an Enum in Mongoose
Enums in Mongoose are declared using the enum property in a schema definition. The enum field can accept an array of allowed values for that particular attribute.
Basic Example
Consider a simple case where you want to define a schema for 'UserRole' with a specific set of allowed roles: 'admin', 'user', and 'guest'.
Here, the role field can only have one of the three specified values. Any attempt to save a document with a role outside these values will result in an error.
Comprehensive Example
Let's consider a more detailed example where we have a task management system, and each task can have a specific status: 'pending', 'in_progress', 'done'.
In this schema:
- The
statusfield is constrained to one of the specified values usingenum. - The
defaultoption is used to automatically assign 'pending' status for new tasks when not explicitly specified.
Validations and Error Handling
When a specified field's value does not match any of the values in the enum list, Mongoose triggers a validation error. Handling these errors is crucial for maintaining data integrity.
Example of Validation Error Handling
In this example, saving the task triggers a validation error because 'completed' is not an allowed status. The validation error can be captured and logged accordingly.
Enum with TypeScript and Mongoose
If your project uses TypeScript, you can further enhance type safety by defining a TypeScript enum alongside your Mongoose schema.
Here, the UserRole TypeScript enum ensures only valid values are passed to or returned from the schema.
Conclusion
Using enums in Mongoose is a powerful way to enforce data constraints and validate inputs, ensuring robust application logic. Whether you're using standard JavaScript or TypeScript, Mongoose's enums allow you to maintain clean and error-resistant code while interacting with MongoDB.
Summary Table
| Feature | Description |
enum in Mongoose | Limits field values to a set of predefined options |
| Basic Enum Example | Role: ['admin', 'user', 'guest'] |
| Advanced Enum Example | Task Status: ['pending', 'in_progress', 'done'] |
| Default Option | Automatically assigns a default value if not provided |
| Validation | Ensures data integrity, triggers errors if values are outside definition |
| TypeScript Support | Enhances type safety with TypeScript enums |
Related reading
- How to create arguments for a Dapper query dynamically
- How to create indexes in MongoDB via .NET
- How to create liquibase changeset for integration tests in springboot?
- How to create postgis extension for postgresql in docker?
- How to create async function using NAPI that return Promises
- How to create folder or key on s3 using AWS SDK for Node.js?
- How to create User/Database in script for Docker Postgres
- how to customize show processlist in mysql?

System Design Fundamentals
Build a strong foundation in designing scalable, reliable distributed systems.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.