Categories
JavaScript Answers

How to create and use enums in Mongoose?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *