runValidators option not working on findByIDAndUpdate or findOneAndUpdate using mongoose

左心房为你撑大大i 提交于 2019-12-11 15:52:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!