pushing object into array schema in Mongoose

mongoose does this for you in one operation.

Contact.findByIdAndUpdate(
    info._id,
    {$push: {"messages": {title: title, msg: msg}}},
    {safe: true, upsert: true},
    function(err, model) {
        console.log(err);
    }
);

Please keep in mind that using this method, you will not be able to make use of the schema’s “pre” functions.

http://mongoosejs.com/docs/middleware.html

As of the latest mogoose findbyidandupdate needs to have a “new : true” optional param added to it. Otherwise you will get the old doc returned to you. Hence the update for Mongoose Version 4.x.x converts to :

Contact.findByIdAndUpdate(
        info._id,
        {$push: {"messages": {title: title, msg: msg}}},
        {safe: true, upsert: true, new : true},
        function(err, model) {
            console.log(err);
        }
    );

Leave a Comment