According to mongoose built-in validators documentations, I can use conditional required field:
const schema = mongoose.Schema({
a: {
type: String,
required: function () {
return this.b === 1
}
},
b: {
type: Number,
required: true
}
});
In this schema the property a
is required only when property b
equals to 1
.
Trying to create a new document works as expected:
Model.create({ b: 1 }); // throws ValidationError (property a is required)
and
Model.create({ b: 2 }); // creates document
My problem is trying to update an existing document and set property b
to 1
so property a
should be required.
Running the following code:
Model.findByIdAndUpdate(model._id, { b: 1 }, { new: true, runValidators: true});
unexpectedly updates the document without throwing an error that property a
is required.
My guess is that the validation is running only for the updated properties (property b
) and not the whole document.
I am not sure if this is the expected behavior or a bug...
Am I missing something? Is there any way to run the validators for the whole document and not only the updated properties without having to manually fetch the document before?