【问题标题】:What is the best way to increment answers count for post like in SO?像SO一样增加帖子的答案计数的最佳方法是什么?
【发布时间】:2016-04-26 12:34:44
【问题描述】:

我正在建立类似 StackOwerflow 的论坛。我的技术栈是 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。进行原子更新的最佳方式是什么?

谢谢。

【问题讨论】:

  • 您是否查看过有关原子性和两阶段提交的 MongoDB 文档?这可能会对你有所帮助。

标签: node.js mongodb mongoose


【解决方案1】:

假设您的问题模型名为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);
        })
    }
}

【讨论】:

  • 感谢您的回复。但你的解决方案不是原子的
  • @Erik 你说的原子是什么意思?
  • 如果你的第二个查询Question.findOneAndUpdate 那么第一个Answer.create 应该是回滚
猜你喜欢
  • 2020-08-22
  • 2021-09-26
  • 1970-01-01
  • 2011-02-27
  • 1970-01-01
  • 2011-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多