简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM