Santiago Esquivel
Santiago Esquivel

Reputation: 380

Insert object in nested array mongodb nodejs

So I am trying to insert an object in parameters and have been unsuccessful. My mongodb structure looks like this:

[
    {
        "_id": "04",
        "name": "test service 4",
        "id": "04",
        "version": "0.0.1",
        "title": "testing",
        "description": "test",
        "protocol": "test",
        "operations": [
            {
                "_id": "99",
                "oName": "test op 52222222222",
                "sid": "04",
                "name": "test op 52222222222",
                "oid": "99",
                "parameters": {},
                "description": "testing",
                "returntype": "test"
            },
            {
                "_id": "58",
                "oName": "test op 52222222222",
                "sid": "04",
                "name": "test op 52222222222",
                "oid": "58",
                "parameters": {},
                "description": "testing",
                "returntype": "test"
            }
        ]
    }
]

I want to be able to add an object into parameters with basic details such as name, id, and type. I am not entirely sure how to tackle this as I have all other CRUD operations implemented up until the parameters part. How should I go about to complete this? I know mongodb has issues when trying to insert something into an array inside an array, so if anyone has any suggestions as to how I can complete this I would really appreciate it. Thanks.

One of the problems is I do not have access to the _id of the root object, but I do have the _id for the operation where I am inserting the parameter. Hence I was trying to insert the parameter using this code:

collection.update({"operations":{"$elemMatch": {"oid": oid}}}, {'$addToSet':{"operations.parameters":  {name: "test"} }}, {safe:true}, function(err, result) {
        if (err) {
            res.send({'error':'An error has occurred'});
        } else {
            res.send(result[0]);
        }
    });

This does not work though.

Upvotes: 2

Views: 3158

Answers (2)

Santiago Esquivel
Santiago Esquivel

Reputation: 380

I was able to complete the insert by using the following code:

collection.update({ "operations": {$elemMatch: {_id:oid}}}, {$addToSet: { "operations.$.parameters" : parameter}}, function(err, result) {
        if (err) {
            res.send({'error':'An error has occurred'});
        } else {
            res.send(result[0]);
        }
});

Just in case anyone needed it.

Upvotes: 4

Salvador Dali
Salvador Dali

Reputation: 222461

This is because you need to use positional operator, The example I am copying from the link is almost the same as in your case:

db.students.update(
   { _id: 4, "grades.grade": 85 },
   { $set: { "grades.$.std" : 6 } }
)

Upvotes: -1

Related Questions