问题
I'm trying to validate an update to a document in mongoose.
I have a validation check for a field as follows:
reason: {
type: String,
enum: ['Finished', 'Incomplete'],
required: function() { return this.status == 'Inactive' }
}
The field status
is an enum as follows:
status: {
type: String,
enum: ['Active', 'Inactive'],
required: true
}
I have a findByIdAndUpdate call in an Express route which uses the option runValidators: true
but if I update one of my documents such as {status: 'Inactive' }
without a reason
defined, it still updates and doesn't throw a ValidationError:
router.put('/:id', (req, res) => {
var id = req.params.id;
ItemInstance.findByIdAndUpdate(id, req.body, {runValidators: true}, (err, itemInstance) => {
if(err)
{
if(err.name == 'CastError')
return res.status(404).send({message: `Cannot find ItemInstance with id ${id}`, error: err})
else
return res.status(500).send(err)
}
return res.status(400).send({message: 'ItemInstance Found and Updated', itemInstance: itemInstance});
});
});
I can't find much information on if the runValidators
option on update() functions work with custom function validators (like mine above) but I don't see why it shouldn't.
Has anybody else run into the issue?
Thanks in advance for any responses.
来源:https://stackoverflow.com/questions/53724348/runvalidators-option-not-working-on-findbyidandupdate-or-findoneandupdate-using