![](/img/trans.png)
[英]How to get document values while validating during a mongoose document update?
[英]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.