Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose enum Validation on String Arrays?

Is it possible to use enum validation on type: [String]?

Example:

var permitted = ['1','2','3'];

var exampleSchema = new Schema({
    factors: {
            type: [String],
            enum: permitted,
            required: "Please specify at least one factor."
    }
});

I would have expected that factors would only be able to contain the values in permitted.

like image 839
clearwater Avatar asked Jun 11 '15 14:06

clearwater


People also ask

What does enum do in mongoose?

Mongoose String and Number types have an enum validator. The enum validator is an array that will check if the value given is an item in the array. If the value is not in the array, Mongoose will throw a ValidationError when you try to save() .

What is ref in Mongoose schema?

The ref option is what tells Mongoose which model to use during population, in our case the Story model. All _id s we store here must be document _id s from the Story model. Note: ObjectId , Number , String , and Buffer are valid for use as refs.

What are enum types?

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.


2 Answers

This is working fine for me ([email protected])

var schema = new mongoose.Schema({
  factors: [{type: String, enum: ['1', '2', '3'], required: ...}] 
  ...
})

Note I'm using an Array of Objects

like image 194
Manu Avatar answered Sep 23 '22 13:09

Manu


As of mongoose version 5.0.6 and higher, the OP issue now works!

 factors: {
            type: [String],
            enum: permitted,
            required: "Please specify at least one factor."
    }

Reference

https://github.com/Automattic/mongoose/issues/6204#issuecomment-374690551

like image 12
Abk Avatar answered Sep 24 '22 13:09

Abk