【问题标题】:Update last_edit with a middleware in Mongoose and Nodejs使用 Mongoose 和 Nodejs 中的中间件更新 last_edit
【发布时间】:2013-02-08 22:28:33
【问题描述】:

让我们考虑一下这个架构:

var elementSchema = new Schema({
  name: String,
  last_edit: { type: Date, default: Date.now }
});

现在,每次我更新任何元素时。name 我希望 mongoose 直接更新 last_edit 时间。

Mongoose Middleware docs 中写道:

var schema = new Schema(..);
schema.pre('save', function (next) {
  // do stuff
  next();
});

我可能会更新它而不是// do stuff,但是要保存的文档没有通过, 有什么提示吗?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    在'save' 中间件中,this 是对正在保存的文档的引用:

    schema.pre('save', function (next) {
      this.last_edit = Date.now();
      next();
    });
    

    【讨论】:

      猜你喜欢
      • 2018-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-28
      • 2020-07-09
      • 2015-03-28
      • 2013-03-30
      相关资源
      最近更新 更多