繁体   English   中英

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

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

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

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

非常感谢!

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

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

这也适用于update/updateOne/updateMany

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

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 钩子。

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

阅读官方文档

暂无
暂无

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

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