Node.JS + Mongo-native:将子对象插入现有对象

时间:2013-03-30 23:38:19

标签: node.js mongodb object

我的用户架构是:

{
    "_id": {"$oid": "515774f2c24007eb57000001"},
    "login": "Ilya",
    "password": "30947a8c9f39b27290a11eabaeec8c89",
}

我正在动态地向用户对象添加研讨会信息。在这段代码之后:

exports.signSeminar = function(user_id, seminar_id, callback) {
    var user_obj_id = BSON.ObjectID.createFromHexString(String(user_id));
    db.collection("users", function(error, collection) {
        collection.findAndModify({
            _id: user_obj_id
        }, [], {
             $set: {
                "seminars": [{
                    "id:": String(seminar_id)
                }]
             }
        }, {}, function(err, result) {
            callback(200);
        });
    });
};

我的对象变为:

{
    "_id": {"$oid": "515774f2c24007eb57000001"},
    "login": "Ilya",
    "password": "30947a8c9f39b27290a11eabaeec8c89",
    "seminars": [
        {
            "id:": "51562509b781ae1d53000001"
        }
    ],
}

我将此代码两次+ shell后,它只是在“研讨会”中重写了对象。我需要插入另一个这样的研讨会对象:

{
    "_id": {"$oid": "515774f2c24007eb57000001"},
    "login": "Ilya",
    "password": "30947a8c9f39b27290a11eabaeec8c89",
    "seminars": [
        {
            "id:": "51562509b781ae1d53000001"
        },
        {
            "id:": "#another_object_id#"
        }
    ],
}

我做错了什么?感谢。

P.S。试过findAndModify,更新,插入,没有运气((

1 个答案:

答案 0 :(得分:2)

$set设置一个值,您需要$push to append to an array

 {
    $push: {
            "seminars": {
                "id:": String(seminar_id)
           }
 }