Push items into mongo array via mongoose Push items into mongo array via mongoose express express

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 it'll 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 you'll 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 it's 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);        }    });)


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}