Mongoose.js更新文档并使用中间件
更新文档和使用更新后中间件(更新后将自动调用的代码)的最佳方法是什么 要使用数据对象更新文档,请执行以下操作:Mongoose.js更新文档并使用中间件,mongoose,Mongoose,更新文档和使用更新后中间件(更新后将自动调用的代码)的最佳方法是什么 要使用数据对象更新文档,请执行以下操作: DocModel.findByIdAndUpdate(id, data, function(err, doc){ // But after update is completed I would like // some model's middleware function to be called, // but there is only: i
DocModel.findByIdAndUpdate(id, data, function(err, doc){
// But after update is completed I would like
// some model's middleware function to be called,
// but there is only: init, save, remove, validate,
// and no update type of middleware
//save middleware is not called in this scenario
//so I can call save for example
doc.save(function(err, doc){
....
// after save is completed middleware will be called
})
})
我想知道这是否可以简化。如果我理解正确,你想要这样的东西。请注意,只有在使用
save()
方法时才会调用中间件
schema.pre('save', function(next) {
this._wasNew = this.isNew;
return next();
});
schema.post('save', function() {
if (this._wasNew) {
console.log('created')
} else {
console.log('updated')
}
});
请参阅相关问题我知道没有pre('update')我希望更新方法使用中间件,但这是不可能的,因为mongoose的更新是原始方法,只映射到mongodb驱动程序的更新。使用上面的代码,您可以模拟post('update'),但是是的,如果必须使用
update
方法而不是save
,则不能使用中间件