【问题标题】:How to access updated document during mongoose post update middleware?如何在猫鼬发布更新中间件期间访问更新的文档?
【发布时间】:2017-05-31 12:05:36
【问题描述】:

我想知道在 mongoose 更新中间件挂钩期间是否有任何可靠/可重用的方式来访问更新的文档。我似乎可以访问的是:

schema.post('update', function (result) {
  console.log(this) // Mongoose Query, no relevant doc info
  console.log(result) // Mongoose CommandResult, no relevant doc info
})

非常感谢!

【问题讨论】:

  • 代替schema.post('update', ...) 尝试schema.post('findOneAndUpdate', function(result) { console.log(result); }); 来访问修改后的文档。

标签: javascript mongodb mongoose middleware


【解决方案1】:

Schema.post('update') 仅用于错误处理(自定义错误消息)

// The same E11000 error can occur when you call `update()`
// This function **must** take 3 parameters. If you use the
// `passRawResult` function, this function **must** take 4
// parameters
Schema.post('update', function(error, res, next) {
  if (error.name === 'MongoError' && error.code === 11000) {
    next(new Error('There was a duplicate key error'));
  } else {
    next(error);
  }
});

如果你想为每个 update() 调用添加一个 updatedAt 时间戳,你可以使用下面的 pre hook。

Schema.pre('update', function() {
  this.update({},{ $set: { updatedAt: new Date() } });
});

Read official docs

【讨论】:

  • 我不是反对者,但这可能是因为您误解了文档。一个错误处理程序中间件必须有 3 或 4 个参数,如果没有,它将被视为一个普通的中间件。它与它无关,它是一个更新后的中间件。
【解决方案2】:

在您在 post 挂钩中收到的 Query 对象中,您可以访问发送到查询的参数。可以这样搞定

_conditions: { id: 'cjauvboxb0000xamdkuyb1fta' }

const id = this._conditions.id

【讨论】:

  • 这仅在您在函数期间将 id 作为参数传递时才有效。如果不是通过id查询,有没有办法获取文档的id?
【解决方案3】:

这也适用于update/updateOne/updateMany

schema.post('update', function (documents) {
  this.model.find(this._conditions).then(documents => {
    console.log(documents.length)
  }
})

【讨论】:

    猜你喜欢
    • 2020-09-14
    • 2015-08-05
    • 1970-01-01
    • 2016-05-24
    • 1970-01-01
    • 1970-01-01
    • 2017-05-10
    • 1970-01-01
    • 2011-10-05
    相关资源
    最近更新 更多