ASD ASD - 4 months ago 69
Node.js Question

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)?

Answer

You can choose between:

Mongose 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
);