Reputation: 355
In my schema I need to have a propery that is an array that must be always not null and not undefined.
So I defined it required, but the validation is not working as I expected, because if I omit the property no error is throw.
In case of simple property (not an array) this work as I expected
const nodeSchema = new Schema({
address: { type: String, required: true },
outputs: { type: [String], required: true }
})
Upvotes: 5
Views: 2791
Reputation: 2039
Just add the "default" as undefined and it will validate the array properly:
const nodeSchema = new Schema({
address: { type: String, required: true },
outputs: { type: [String], required: true, default: undefined },
})
Upvotes: 1
Reputation: 21
Array implicitly have a default value of [] (empty array).
if you add default: undefined
it will fix the issue.
Upvotes: 1
Reputation: 239
I think you can fix it adding a custom validator like this:
const nodeSchema = new Schema({
address: { type: String, required: true },
outputs: {
type: [String],
required: true,
validate: [(value) => value.length > 0, 'No outputs'],
}
})
I hope it helps you.
Upvotes: 7
Reputation: 355
Arrays implicitly have a default value of [] (empty array).
This was the problem
Upvotes: 0