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
.
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() .
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With