将新对象插入mongoose的子文档数组字段中

ASD*_*ASD 4 database mongoose mongodb node.js

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

上面是json格式的模型(来自mongobooter)让我们说"行",我有_id和dots.id,我想将新对象添加到位置.那怎么能这样做(使用猫鼬)?

Dar*_*rio 14

你可以选择:

Mongose对象方式:

document.dots[0].location.push({ /* your subdoc*/ });
document.save(callback);
Run Code Online (Sandbox Code Playgroud)

Mongo/Mongoose Query(使用$push$运算符):

YourModel.update(
  {_id: /* doc id */, 'dots.id': /* subdoc id */ },
  {$push: {'dots.$.location': { /* your subdoc */ }},
  callback
);
Run Code Online (Sandbox Code Playgroud)