Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Create and Use Enum in Mongoose

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 program as follows:

My schema is:

var RequirementSchema = new mongooseSchema({    status: {         type: String,         enum : ['NEW','STATUS'],         default: 'NEW'     }, }) 

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

Thanks

like image 913
Prabjot Singh Avatar asked Mar 27 '15 11:03

Prabjot Singh


People also ask

What is 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. E.g: var userSchema = new mongooseSchema({ userType: { type: String, enum : ['user','admin'], default: 'user' }, }) Follow this answer to receive notifications.

What is enum variable?

An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.

What is enum in JavaScript?

Enums are one of the few features TypeScript has which is not a type-level extension of JavaScript. Enums allow a developer to define a set of named constants. Using enums can make it easier to document intent, or create a set of distinct cases.


1 Answers

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

like image 118
Mindstormer619 Avatar answered Oct 08 '22 19:10

Mindstormer619