f1nn f1nn - 5 months ago 19
Node.js Question

Node.JS + Mongo-native: Insert child object to existing object

My user schema is:

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


I'm doing dynamic adding seminars info to user object. After this code:

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);
});
});
};


my object becomes:

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


After I shell this code twice+ times, it just re-writes children object in "seminars". And I need to insert just another seminar object like this:

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


What I'm doing wrong? Thanks.

P.S. Tried findAndModify, update, unsert, no luck((

Answer

$set sets a value, you want $push to append to an array.

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