Easy way to increment Mongoose document versions for any update queries?

自闭症网瘾萝莉.ら 提交于 2019-12-04 04:10:52
Antoine

I'd say this is the way to go. pre middleware fits exactly this need, and I don't know any other way. In fact this is what I'm doing in all my schemas.

What you need to be aware of though, is the difference between document and query middleware. Document middleware are executed for init, validate, save and remove operations. There, this refers to the document:

schema.pre('save', function(next) {
  this.increment();
  return next();
});

Query middleware are executed for count, find, findOne, findOneAndRemove, findOneAndUpdate and update operations. There, this refers to the query object. Updating the version field for such operations would look like this:

schema.pre('update', function( next ) {
  this.update({}, { $inc: { __v: 1 } }, next );
});

Source: mongoose documentation.

For me the simplest way to do that is :

clientsController.putClient = async (req, res) => {

const id = req.params.id;
const data = req.body;
data.__v++;

await Clients.findOneAndUpdate({ _id: id }, data)
    .then( () => 
    {
        res.json(Ok);
    }
    ).catch ( err => {
        Error.code = '';
        Error.error = err;
        res.json(Error);
    })

};

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