node.js – Push items into mongo array via mongoose

node.js – Push items into mongo array via mongoose

Assuming, var friend = { firstName: Harry, lastName: Potter };

There are two options you have:

Update the model in-memory, and save (plain javascript array.push):

person.friends.push(friend);
person.save(done);

or

PersonModel.update(
    { _id: person._id }, 
    { $push: { friends: friend } },
    done
);

I always try and go for the first option when possible, because itll respect more of the benefits that mongoose gives you (hooks, validation, etc.).

However, if you are doing lots of concurrent writes, you will hit race conditions where youll end up with nasty version errors to stop you from replacing the entire model each time and losing the previous friend you added. So only go to the former when its absolutely necessary.

The $push operator appends a specified value to an array.

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

$push adds the array field with the value as its element.

Above answer fulfils all the requirements, but I got it working by doing the following

var objFriends = { fname:fname,lname:lname,surname:surname };
Friend.findOneAndUpdate(
   { _id: req.body.id }, 
   { $push: { friends: objFriends  } },
  function (error, success) {
        if (error) {
            console.log(error);
        } else {
            console.log(success);
        }
    });
)

node.js – Push items into mongo array via mongoose

Use $push to update document and insert new value inside an array.

find:

db.getCollection(noti).find({})

result for find:

{
    _id : ObjectId(5bc061f05a4c0511a9252e88),
    count : 1.0,
    color : green,
    icon : circle,
    graph : [ 
        {
            date : ISODate(2018-10-24T08:55:13.331Z),
            count : 2.0
        }
    ],
    name : online visitor,
    read : false,
    date : ISODate(2018-10-12T08:57:20.853Z),
    __v : 0.0
}

update:

db.getCollection(noti).findOneAndUpdate(
   { _id: ObjectId(5bc061f05a4c0511a9252e88) }, 
   { $push: { 
             graph: {
               date : ISODate(2018-10-24T08:55:13.331Z),
               count : 3.0
               }  
           } 
   })

result for update:

{
    _id : ObjectId(5bc061f05a4c0511a9252e88),
    count : 1.0,
    color : green,
    icon : circle,
    graph : [ 
        {
            date : ISODate(2018-10-24T08:55:13.331Z),
            count : 2.0
        }, 
        {
            date : ISODate(2018-10-24T08:55:13.331Z),
            count : 3.0
        }
    ],
    name : online visitor,
    read : false,
    date : ISODate(2018-10-12T08:57:20.853Z),
    __v : 0.0
}

Leave a Reply

Your email address will not be published.