如何使用node.js在嵌套数组中为mongodb添加新对象?

时间:2016-03-06 05:23:21

标签: javascript node.js mongodb

我在mongoDB中存储了以下数据库结构:

    "location" : "Halifax",
    "students" : [
    {
        "name": "Mike",
        "ID": "B00123456",
        "images": [
            {
                "image_url":"",
                "image_id":""
            }
        ]
    },
    {
        "name": "Rinan",
        "ID": "B00999999",
        "images": [
            {
                "image_url":"",
                "image_id":""
            }
        ]
    }
   ]

我的问题是:如何将一个新对象推送到名为Mike的学生中的图像数组,该学生的ID为“B00123456”,我知道我应该使用mongoDB的更新和设置方法。但我找不到实现这一目标的方法。我想要的结果是:

"location" : "Halifax",
"students" : [
{
    "name": "Mike",
    "ID": "B00123456",
    "images": [
        {
            "image_url":"",
            "image_id":""
        },
        {
            "image_url":"www.example.com",
            "image_id":"uqxhqbxqx_1219"
        }
    ]
},
{
    "name": "Rinan",
    "ID": "B00999999",
    "images": [
        {
            "image_url":"",
            "image_id":""
        }
    ]
}
]

以下是我正在尝试使用MongoDB的更新并设置:

    // Connect and create a new doc
    MongoClient.connect('mongodb://username:password@iad1- mongos0.objectrocket.com:someNode/db_name', functionb(err, db) {
    if (err) {
        console.dir(err);
        console.log("error connected to mongodb");
    } else {
        var collection = db.collection('student_info_collection');
        var student_name = req.body.name;
        var student_id = req.body.ID;
        collection.update( 
                 { location:"Halifax" },
                 { ID:student_id}
                 { name: student_name},
                 {$push: { 
                            {
                                "images": [
                                    {
                                        "image_url":"www.example.com",
                                        "image_id":"uqxhqbxqx_1219"
                                    }
                             ]
                      } 
                 }
         }, function(err,result){
            if (err)
                console.log("Something's wrong");
            else
                res.sendStatus(200);
         }
        );
    }
    });

任何帮助?

1 个答案:

答案 0 :(得分:2)

update()功能

 update(selector, document[, options][, callback])

第一个参数是selector,请尝试这个

    var student_name = req.body.name;
    var student_id = req.body.ID;
    collection.update( 
             { location:"Halifax", 
               'students.ID': student_id, 
               'students.name': student_name},
             {$push: { "students.$.images": 
                                {
                                    "image_url":"www.example.com",
                                    "image_id":"uqxhqbxqx_1219"
                                }
                     }
     }, function(err,result){