Saurabh B Saurabh B - 2 months ago 42
Node.js Question

mongoose findByIdAndUpdate updating only one field in the document

I am trying to increment upvotes when the user clicks on some button and also store his stormpath User ID (req.user.href) inside an array.

TRY 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);
})
}


RESULT:
Only upvoters array is correctly updated. Upvotes are not incremented.

TRY 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);
})


RESULT:
Only Upvotes get incremented, upvoters array is not updated.

TRY 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);
})


RESULT : Nothing Happens

WHAT I WANT TO DO : Update the Upvoters array and increment upvotes by 1.

Answer

You need to but both the $inc and $push operators into the same object:

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);
})
Comments