2016-06-09 42 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()',这在并发性方面是不安全的。 –