user10140016
user10140016

Reputation:

How to allow only certain string values inside a Mongodb array using mongoose?

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

Answers (1)

Rohit Kashyap
Rohit Kashyap

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

Related Questions