【问题标题】:Insert a new object into a sub-document array field in mongoose将新对象插入到 mongoose 中的子文档数组字段中
【发布时间】:2016-12-09 15:39:15
【问题描述】:
[{
    "_id" : ObjectId("579de5ad16944ccc24d5f4f1"),
    "dots" : 
    [
        {
            "id" : 1,
            "location" : 
            [
                 {
                    "lx" : 10,
                    "ly" : 10
                 }
            ]
        },
        {
            "id" : 2,
            "location" : [{}]
        }
    ]
}]

以上是模型的 json 格式(来自 mongobooter)让我们说“线”,我有 _id 和 dots.id,我想将新对象添加到位置。那我该怎么做(使用猫鼬)?

【问题讨论】:

  • 哪个位置?点数组?
  • “位置”与点数组对象.....

标签: node.js mongodb mongoose database


【解决方案1】:

您可以选择:

Mongoose 对象方式:

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

Mongo/Mongoose 查询(使用$push 和$ operator):

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

【讨论】:

  • 如果我要推送多个数据怎么办?
  • 如果不能使用点的索引,你会如何处理?
猜你喜欢
  • 2021-01-10
  • 1970-01-01
  • 2019-02-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-04
  • 2018-09-04
  • 2020-02-07
  • 1970-01-01
相关资源
最近更新 更多