使用 `findOneAndUpdate` Mongoose 钩子设置更新后的值

Fiz*_*zix 1 mongoose mongodb

我正在尝试将findOneAndUpdate钩子与 Mongoose一起使用(在此处详细讨论),尽管我在尝试设置更新后的值时遇到了一些问题。

例如:

MySchema.findOneAndUpdate({_id: fj394hri3hfj}, {$push: {comments: myNewComment}})
Run Code Online (Sandbox Code Playgroud)

将触发以下钩子:

MySchema.post('findOneAndUpdate', function(result) {
    this.update({}, { totalNumberOfComments: result.comments.length });
});
Run Code Online (Sandbox Code Playgroud)

虽然,钩子会$pushcommentsmyNewComment一遍,因此使重复的条目。

我使用this.update({}, {....})而不是this.findOneAndUpdate({}, {....})在钩子内,这样post钩子就不会被无限调用。

totalNumberOfComments是完全设置的长度comments.length

因此,似乎this.update({}, {....})只是将更多更新字段推送到this.

我怎样才能totalNumberOfComments在我的钩子中设置而不是再次推送评论?

Use*_*r97 5

问题似乎出在您在 post findOneAndUpdatehook 中编写的更新查询中。尝试将其替换为,

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

希望它应该有效。

我还建议,使用findsave更新文档而不是findOneAndUpdate它的 post 钩子。


编辑:

如果您需要使用findand save,您可以将上面的代码替换为:

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

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

       console.log("Document Updated");       
    }); 
});
Run Code Online (Sandbox Code Playgroud)

它应该工作。