node.js - mongoose findByIdAndUpdate 仅更新文档中的一个字段

标签 node.js mongodb mongoose mongodb-query

我试图在用户点击某个按钮时增加赞成票,并将他的 stormpath 用户 ID (req.user.href) 存储在一个数组中。

尝试 1:

if (newUpvoters = found_post[0].upvoters.indexOf(req.user.href) == -1) {
    Problem.findByIdAndUpdate(found_post[0].id,  
        { $push: { upvoters:  req.user.href }}
        , {$inc: { upvotes : 1 } }, function (err, post) {
                if (err) return next(err);
                res.json(post);
    })
}

结果: 只有 upvoters 数组被正确更新。赞成票不会增加。

尝试 2:

Problem.findByIdAndUpdate(found_post[0].id,  
    {$inc: { upvotes : 1 } }, 
    { $push: { upvoters:  req.user.href }}, function (err, post) {
        if (err) return next(err);
        res.json(post);
})

结果: 只有 Upvotes 会增加,upvoters 数组不会更新。

尝试 3:

Problem.findByIdAndUpdate(found_post[0].id,  
    {$set :
        {$inc: { upvotes : 1 } , 
         $push: { upvoters:  req.user.href }}
    }, function (err, post) {
        if (err) return next(err);
        res.json(post);     
     })

结果:什么都没发生

我想做什么:更新 Upvoters 数组并将 upvotes 增加 1。

最佳答案

您需要将 $inc$push 运算符都放入同一个对象中:

Problem.findByIdAndUpdate(found_post[0].id,  
    { $inc: { upvotes : 1 }, 
      $push: { upvoters:  req.user.href }
    }, function (err, post) {
        if (err) return next(err);
        res.json(post);
})

关于node.js - mongoose findByIdAndUpdate 仅更新文档中的一个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39818119/

相关文章:

mongodb - 如何导出/转储 mongodb 数据库?

node.js - 类型错误 : Cannot use 'in' operator to search for 'pluralization' in undefined

node.js - findAndModify 或 findOneAndUpdate - "is not a function"

mongodb - Mongoose 模式,如何在一个模式中嵌套对象?

api - REST:处理计算的和相关的资源属性

node.js - 如何添加对模型的引用?

javascript - 在 openshift Node js 应用程序中获取请求

node.js - 我无法在 NodeJs 服务器中接收 POST 请求

javascript - 使用 CSS 的自动索引行未按预期运行

node.js - Mongoose 模式虚拟和异步等待