简体   繁体   English

如何在猫鼬后期更新中间件期间访问更新的文档?

[英]How to access updated document during mongoose post update middleware?

I'm wondering if there is any reliable/reusable way to access the updated document during a mongoose post update middleware hook.我想知道在猫鼬后期更新中间件挂钩期间是否有任何可靠/可重用的方式来访问更新的文档。 All I seem to have access to is:我似乎可以访问的是:

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

Thank you very much!非常感谢!

In the Query object you receive in the post hook, you have access to the parameters sent to the query.在 post 挂钩中收到的 Query 对象中,您可以访问发送到查询的参数。 You can get it like this你可以这样得到

 _conditions: { id: 'cjauvboxb0000xamdkuyb1fta' } const id = this._conditions.id

this also works on update/updateOne/updateMany这也适用于update/updateOne/updateMany

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

Schema.post('update') is only used in error handling (custom error messages) 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);
  }
});

If you wanted to add an updatedAt timestamp to every update() call for example, you would use the following pre hook.例如,如果您想为每个 update() 调用添加一个 updatedAt 时间戳,您可以使用以下 pre 钩子。

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

Read official docs阅读官方文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM