为任何更新查询增加Mongoose文档版本的简便方法? [英] Easy way to increment Mongoose document versions for any update queries?
问题描述
我想开始利用Mongooses文档版本控制(__v key)。我实际上在增加版本值时遇到了问题,然后我发现在执行查询时你必须添加 this.increment()
。
I want to start taking advantage of Mongooses document versioning (__v key). I was having an issue actually incrementing the version value, then I found that you have to add this.increment()
when executing a query.
有没有办法自动增加?目前,我刚刚将其添加到 pre 中间件以获取更新类型查询:
Is there a way to have automatically incremented? For now, I just added it to the pre middleware for a update-type queries:
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()
} )
} )
}
哪个似乎有用..但我觉得在Mongoose中已经有办法做到这一点..我错了吗?
Which seems to work.. But I kinda thought there would already be a way to do this within Mongoose.. am I wrong?
推荐答案
我会说这是要走的路。 预中间件完全适合这种需求,我不知道其他任何方式。事实上,这就是我在所有模式中所做的事情。
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.
你需要注意的是, document 之间的区别和查询中间件。
文档中间件执行 init
,验证
,保存
和删除
操作。在那里,这个
指的是文件:
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();
});
查询中间件执行 count
,查找
, findOne
, findOneAndRemove
, findOneAndUpdate
和更新
操作。在那里,这个
指的是查询对象。更新此类操作的版本字段如下所示:
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 );
});
资料来源: mongoose文档。
这篇关于为任何更新查询增加Mongoose文档版本的简便方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!