2016-04-25 68 views
-1

我正在構建像StackOwerflow這樣的論壇。我的技術堆棧是NodeJS/MongoDB/Mongoose。我的問題是我不明白如何在添加新答案時對問題帖子進行原子更新。什麼是最好的方式來增加答案計數爲後在SO裏?

看我的帖子集合:

[{ 
    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。什麼是進行原子更新的最佳方式?

謝謝。

+0

你有沒有插入原子和兩階段提交MongoDB的文檔?這可能會幫助你。 –

回答

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); 
     }) 
    } 
} 
+0

感謝您的回覆。但你的解決方案不是原子的 – Erik

+0

@Erik你是什麼意思的原子? – ayushgp

+0

如果你的第二個查詢'Question.findOneAndUpdate',那麼第一個'Answer.create'應該是回滾 – Erik

相關問題