Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/148.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mongoose.js更新文档并使用中间件_Mongoose - Fatal编程技术网

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
,则不能使用中间件