小编Sau*_*h B的帖子

猫鼬 findByIdAndUpdate 只更新文档中的一个字段

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

尝试 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);
    })
}
Run Code Online (Sandbox Code Playgroud)

结果: 只有 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);
})
Run Code Online (Sandbox Code Playgroud)

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

尝试 3:

Problem.findByIdAndUpdate(found_post[0].id,  
    {$set :
        {$inc: { upvotes : …
Run Code Online (Sandbox Code Playgroud)

mongoose mongodb node.js mongodb-query

4
推荐指数
1
解决办法
5409
查看次数

标签 统计

mongodb ×1

mongodb-query ×1

mongoose ×1

node.js ×1