0

更新文档和使用更新后中间件(更新后将自动调用的代码)的最佳方法是什么。

要使用数据对象更新文档,我执行以下操作:

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

我想知道这是否可以简化。

4

1 回答 1

0

如果我理解正确,你想要这样的东西。请注意,仅在使用方法时才调用中间件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')
    }
});
于 2013-05-23T13:56:37.867 回答