增加答案的最佳方法是什么?

时间:2016-04-25 09:54:47

标签: node.js mongodb mongoose

我正在构建像StackOwerflow这样的论坛。我的tehcnology堆栈是NodeJS / MongoDB / Mongoose。我的问题是,我不了解如何在添加新答案时对问题帖子进行原子更新。

查看我的帖子集:

[{
  id: 1,
  title: 'How to learn JavaScript'
  body: 'Subject',
  answers_count: 2
},
{
  id: 2,
  parentId: 1,
  body: 'Read book'
},
{
  id: 3,
  parentId: 1,
  body: 'Watch YouTube'
}]

当我添加或删除新答案时,我需要在parant帖子中增加answers_count。进行原子更新的最佳方法是什么?

感谢。

1 个答案:

答案 0 :(得分:0)

假设您的问题模型名为Question并回答模型Answer。然后你可以像这样进行更新:

Answer.create({
    //the answer object you have
},
function(err,res){
    if(err) 
        console.log(err);
    else {
        Question.findOneAndUpdate({
            id: //answer's parent id
        }, 
        {
            $inc:{ answer_count:1 }
        },
        function(err,res){
            if(err) 
                console.log(err);
            else 
                console.log("Answer count incremented. The updated question is "+res);
        })
    }
}
相关问题