为任何更新查询增加 Mongoose 文档版本的简单方法

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

本文关键字:版本 简单 方法 文档 Mongoose 任何 更新 查询 增加      更新时间:2023-09-26

我想开始利用猫鼬文档版本控制(__v键)。我实际上遇到了增加版本值的问题,然后我发现您必须在执行查询时添加this.increment()

有没有办法自动递增?现在,我只是将其添加到中间件中以进行更新类型的查询:

module.exports = Mongoose => {
    const Schema = Mongoose.Schema
    const modelSchema = new Schema( {
        name: Schema.Types.String,
        description: Schema.Types.String
    } )
    // Any middleware that needs to be fired off for any/all update-type queries
    _.forEach( [ 'save', 'update', 'findOneAndUpdate' ], query => {
        // Increment the Mongoose (__v)ersion for any updates
        modelSchema.pre( query, function( next ) {
            this.increment()
            next()
        } )
    } )
}

这似乎有效..但我有点认为猫鼬已经有办法做到这一点了。我错了吗?

我会说这是要走的路。中间件完全符合这种需求,我不知道任何其他方法。事实上,这就是我在所有架构中所做的。

但是,您需要注意的是文档查询中间件之间的区别。文档中间件是为initvalidatesaveremove操作而执行的。在那里,this指的是文档:

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

查询中间件用于countfindfindOnefindOneAndRemovefindOneAndUpdateupdate操作。在那里,this是指查询对象。更新此类操作的版本字段如下所示:

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

资料来源:猫鼬文献。

对我来说,最简单的方法是:

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);
    })

};