【问题标题】:Update last_edit with a middleware in Mongoose and Nodejs使用 Mongoose 和 Nodejs 中的中间件更新 last_edit
【发布时间】:2026-01-25 14:50:01
【问题描述】:

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

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

    【讨论】: