簡體   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