我試圖使用Mongoose的findOneAndUpdate
掛鉤(詳細討論here),儘管我在嘗試設置值更新後有一些問題。使用findOneAndUpdate` Mongoose鉤子設置值更新後的值
例如:
MySchema.findOneAndUpdate({_id: fj394hri3hfj}, {$push: {comments: myNewComment}})
將觸發以下鉤:
MySchema.post('findOneAndUpdate', function(result) {
this.update({}, { totalNumberOfComments: result.comments.length });
});
雖然,鉤將$push
到comments
再次myNewComment
,因此使重複的條目。
我使用this.update({}, {....})
而不是this.findOneAndUpdate({}, {....})
內的掛鉤,以便post
掛鉤不被無限調用。
totalNumberOfComments
完全設置爲comments.length
的長度。
因此,好像this.update({}, {....})
只是將更多更新字段推送到this
上已有的更新字段。
如何在我的掛鉤中設置totalNumberOfComments
而不是重新推送評論?
你確定發佈'findOneAndUpdate'掛鉤在你的情況下被調用嗎? – Raeesaa
嗯,是的,這就是它創建重複的原因,因爲它在我的'findOneAndUpdate'調用中被調用,然後再次在鉤子中調用。我也在鉤子裏做了一個'console.log(this)'並且它成功記錄了。問題是,'this'仍然保存'$ push:{comments:myNewComment}'更新,並且鉤子也只是推送一個'$ set'更新,因此它有'$ push'兩次。 – Fizzix
好的。是否真的有必要使用post hook?你可以只用'find'和'save'來代替。 – Raeesaa