Reputation: 665
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
.
Upvotes: 33
Views: 23217
Reputation: 21
Mongoose before version 4.0 didn't support validation on Schema static methods like .update
, .findByIdAndUpdate
, .findOneAndUpdate
.
But it supports on instance method document.save()
.
So, either use document.save()
for inbuilt initiating validation
or this { runValidators: true }
with methods like .update
, .findByIdAndUpdate
, .findOneAndUpdate
.
reference: Mongoose .update() does not trigger validation checking
Upvotes: 2
Reputation: 649
you can use something like this
{
factors: [
{
type: [String],
enum: ['1', '2', '3'],
},
],
}
Upvotes: 0
Reputation: 1683
if you have enuns or you have object enuns
brand: {
type: String,
required: true,
enum: Object.values(TypeBrandEnum)
},
Upvotes: 0
Reputation: 419
TRY THIS
let inventory_type_enum = ["goods", "services"];
inventory_type: {
type: String,
enum: inventory_type_enum,
validate: {
// validator: (inventory_type) => !inventory_type.enum.includes(inventory_type),
validator: (inventory_type) => inventory_type_enum.includes(inventory_type),
message: languages('general_merchandise_model','inventory_type')
},
required : [true, languages('general_merchandise_model','inventory_type_required')],
},
Upvotes: 1
Reputation: 2233
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
Upvotes: 13
Reputation: 10293
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
Upvotes: 60