How to Create and Use Enum in Mongoose

849    Asked by AmitSinha in Spark , Asked on May 12, 2021

I am trying to create and use an enum type in Mongoose. I checked it out, but I'm not getting the proper result. I'm using enum in my mongoose schema as follows:

var RequirementSchema = new mongoose.Schema({ 
status: { 
type: String, 
enum : ['NEW', 'STATUS'], 
default: 'NEW' 

But I am a little bit confused here, how can I put the value of an enum like in Java NEW("new"). How can I save an enum into the database according to its enumerable values? I am using it in express node.js.

Answered by Coleman Garvin

To Create and Use mongoose enum, mongoose has various inbuilt validators. Strings have enum as one of the validators. So enum creates a validator and checks if the value is given in an array.

var userSchema = new mongooseSchema({ 
userType: {
type: String,
enum : ['user','admin'],
default: 'user'

Your Answer


Parent Categories