【问题标题】:Mongoose.js update doc and use middlewareMongoose.js 更新文档并使用中间件
【发布时间】:2013-02-03 11:46:36
【问题描述】:

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

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

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

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

【问题讨论】:

标签: mongoose


【解决方案1】:

如果我理解正确,你想要这样的东西。请注意,只有在使用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')
    }
});

【讨论】:

  • 嗯,我想要更新方法的中间件,但这是不可能的,因为 mongoose 的更新是原始方法,它只映射到 mongodb 驱动程序的更新。
  • 使用上面的代码你可以模拟一个post('update'),但是是的,如果你必须使用update方法而不是save你不能使用中间件
猜你喜欢
  • 2012-11-21
  • 1970-01-01
  • 2018-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-07
  • 1970-01-01
相关资源
最近更新 更多