2016-06-09 67 views
0

我試圖使用Mongoose的findOneAndUpdate掛鉤(詳細討論here),儘管我在嘗試設置值更新後有一些問題。使用findOneAndUpdate` Mongoose鉤子設置值更新後的值

例如:

MySchema.findOneAndUpdate({_id: fj394hri3hfj}, {$push: {comments: myNewComment}}) 

將觸發以下鉤:

MySchema.post('findOneAndUpdate', function(result) { 
    this.update({}, { totalNumberOfComments: result.comments.length }); 
}); 

雖然,鉤將$pushcomments再次myNewComment,因此使重複的條目。

我使用this.update({}, {....})而不是this.findOneAndUpdate({}, {....})內的掛鉤,以便post掛鉤不被無限調用。

totalNumberOfComments完全設置爲comments.length的長度。

因此,好像this.update({}, {....})只是將更多更新字段推送到this上已有的更新字段。

如何在我的掛鉤中設置totalNumberOfComments而不是重新推送評論?

+0

你確定發佈'findOneAndUpdate'掛鉤在你的情況下被調用嗎? – Raeesaa

+0

嗯,是的,這就是它創建重複的原因,因爲它在我的'findOneAndUpdate'調用中被調用,然後再次在鉤子中調用。我也在鉤子裏做了一個'console.log(this)'並且它成功記錄了。問題是,'this'仍然保存'$ push:{comments:myNewComment}'更新,並且鉤子也只是推送一個'$ set'更新,因此它有'$ push'兩次。 – Fizzix

+0

好的。是否真的有必要使用post hook?你可以只用'find'和'save'來代替。 – Raeesaa

回答

4

這個問題似乎是在你寫在帖子findOneAndUpdate鉤子的更新查詢中。嘗試替換它,

MySchema.post('findOneAndUpdate', function(result) { 
    this.totalNumberOfComments = this.result.comments.length; 
    this.save(function(err) { 
     if(!err) { 
      console.log("Document Updated"); 
     } 
    }); 
}); 

並希望它應該工作。

我還建議,使用findsave更新文檔,而不是findOneAndUpdate及其後掛鉤。


編輯:

在你需要使用findsave情況下,你可以將其替換上面的代碼:

MySchema.findById(fj394hri3hfj, function(err, doc){ 

    doc.comments.push(myNewComment); 
    doc.totalNumberOfComments += 1; 
    doc.save(function(err){ 

     console.log("Document Updated");  
    }); 
}); 

,它應該工作。

+1

決定與您的第二個選項一起設置保存期間的評論長度。也許更好地做到這一點,我想在未來允許刪除評論。將在12小時內獎勵賞金。謝謝! – Fizzix

+0

注意以這種方式使用'.save()',這在併發性方面是不安全的。 –