db2791 db2791 - 4 months ago 22
Node.js Question

Mongoose multiple $push to multiple arrays

I'm trying to update more than one database entry in my Mongodb:

User.findByIdAndUpdate(req.user._id,
{$push: {people_seen: person_id}},
{$push: {people_liked: person_id}},
function(err, usr){
console.log(req.user);
res.json({success: true});
});


However, only
people_seen
is getting saved.

Answer

You are using the $push operator multiple time, in which case only the last operation is maintained. The correct syntax is:

{ $push: { <field1>: <value1>, ... } }

thus the right query is:

User.findByIdAndUpdate(req.user._id,
    { $push: { people_seen: person_id, people_liked: person_id }},
    function(err, usr){
        console.log(req.user);
        res.json({ success: true });
});