Reputation:
I'm creating a server side application using Node.js
and Mongodb
. And i'm using Mongoose
package to access MongoDB
database. And, i would want my Mongoose array to only allow certain values to be pushed inside it. For eg. If i have configured my mongoose
array to support values like admin
, user
and course
, is there any way mongoose forbid pushing of values anything other than admin
,user
and course
into the array ?
Upvotes: 1
Views: 3082
Reputation: 1592
Try this:
var schema = new mongoose.Schema({
somefield: {type: String, enum: ['admin', 'user', 'course'], required: ...}
...
})
The enum
attribute will only allow the mentioned values. You can also set a custom error message to check if the request body contains anything other than these specified fields.
Read more here: https://mongoosejs.com/docs/validation.html#built-in-validators
Upvotes: 11