Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

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.

2 Answers

0 votes
by (106k points)

To Create and Use Enum in Mongoose, mongoose has several 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' 

}, 

})

0 votes
by (107k points)

The enums here are basically String objects. Just change the enum line to the enum: ['NEW', 'STATUS'] instead. You have a typo there with your reference marks.

Related questions

0 votes
2 answers
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...