在mongoose的子文档数组字段中插入一个新对象 [英] Insert a new object into a sub-document array field in mongoose

查看:134
本文介绍了在mongoose的子文档数组字段中插入一个新对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

推荐答案

您可以选择:

猫鼬对象方式:

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

Mongo/猫鼬查询(使用 $push $运算符):

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

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

这篇关于在mongoose的子文档数组字段中插入一个新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆