Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert a new object into a sub-document array field in mongoose

[{
    "_id" : ObjectId("579de5ad16944ccc24d5f4f1"),
    "dots" : 
    [
        {
            "id" : 1,
            "location" : 
            [
                 {
                    "lx" : 10,
                    "ly" : 10
                 }
            ]
        },
        {
            "id" : 2,
            "location" : [{}]
        }
    ]
}]

Above is json format of model (from mongobooter) let's say "lines", and i have _id and dots.id and i want to add new object into location. then how can i do that (using mongoose)?

like image 985
ASD Avatar asked Aug 03 '16 19:08

ASD


1 Answers

You can choose between:

Mongoose Object-way:

document.dots[0].location.push({ /* your subdoc*/ });
document.save(callback);

Mongo/Mongoose Query (using $push and $ operator):

YourModel.update(
  {_id: /* doc id */, 'dots.id': /* subdoc id */ },
  {$push: {'dots.$.location': { /* your subdoc */ }},
  callback
);
like image 128
Dario Avatar answered Nov 15 '22 23:11

Dario