How to create and use enums in Mongoose?

Sometimes, we want to create and use enums in Mongoose.

In this article, we’ll look at how to create and use enums in Mongoose.

How to create and use enums in Mongoose?

To create and use enums in Mongoose, we can set the enum property when we create our schema.

For instance, we write

const UserSchema = new Schema({
  userType: {
    type: String,
    enum: ['user', 'admin'],
    default: 'user'
  },
})

to create the UserSchema with the userType column.

We make it a string column by setting type to String.

And we set enum to an array of possible values we want the userType to have.

Also, we set the default value for userType to 'user'.

Conclusion

To create and use enums in Mongoose, we can set the enum property when we create our schema.