mongoose – add to an existing array

a new language and a new database means that there are new ways to do things. mongodb is a document-oriented database which means that updating your document is a little more complex than your standard SQL update.

suppose you have a document:

1
2
3
4
5
6
7
8
9
10
11
{
    _id: 1,
    items: [
        {
            itemId: 1,
            title: 'ipod nano black',
            price: '42',
            _id: 1001
        }
    ]
}

and you want to add a new item to the items array in your document. after some digging around, it looks like this works:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
var item = {
    title: 'title of the new item',
    price: '4242'
};
 
// find by document id and update
collection.findByIdAndUpdate(
    1,
    {$push: {items: item}},
    {safe: true, upsert: true},
    function(err, model) {
        console.log(err);
    }
);
 
// find by some conditions and update
collection.findOneAndUpdate(
    {_id: req.query.id},
    {$push: {items: item}},
    {safe: true, upsert: true},
    function(err, model) {
        console.log(err);
    }
);

where collection is your instance of the model you are updating. you can either findByIdAndUpdate if you have the document id handy, otherwise you can findOneAndUpdate and use some conditions to find the record that you want to update.

ugh, this is really simple stuff, it should be easy, but the mongoose documentation would really benefit from a few examples.

8 thoughts on “mongoose – add to an existing array”

  1. I am just seeming both for blog sites which give independent, nutritious commentary on all difficulties or blogging sites which have a liberal or droppedwing slant. Thank you.. kaabdedakkbfebee

  2. Thanks! Even two years after you published this, it’s still useful for people having issues with Mongoose. Thanks for taking the time to write this up!

Leave a Reply

Your email address will not be published.