DukeLover
DukeLover

Reputation: 2457

How to update a nested array in Node.js + Mongo DB where index value is known

I want to update nested array in Mongo DB (using Node.js). I am able to get the array index location.

How can I update same ? I am facing some problem while using escape character in $set

Here is what I am doing :

testCollection.update({
        "uniqueID": someID,
        "topLevelObject.innerObjectValue": innerObjectVal
    }, {
        $set: {

            'array.' + outerArrayIndex + '.value': updatedValue,

        }

    }, function(err, result) {

        if (err) {
            console.log("Error occurred while updating db info");
        }

    }
);

Upvotes: 0

Views: 1149

Answers (1)

wdberkeley
wdberkeley

Reputation: 11671

It's hard to tell what the problem is because you have not included an example document or shown an error message or what goes wrong. Assuming your document looks like

{
    "_id" : 0,
    "array" : [{ "value" : 2 }, { "value" : 6 }]
}

then your above query should work, e.g.

db.test.update({ "_id" : 0 }, { "$set" : { "array.1.value" : 906 } })

will modify the document to

{
    "_id" : 0,
    "array" : [{ "value" : 2 }, { "value" : 906 }]
}

I omitted the other query condition because it isn't necessary with a unique id specified - perhaps the condition isn't matching any documents?

If you document looks like

{
    "_id" : 0,
    "array" : [2, 6]
}

then you don't need the .value in the update query:

db.test.update({ "_id" : 0 }, { "$set" : { "array.1" : 906 } })

I'd also check that the string concatenation with the variable outerArrayIndex is producing the correct field path.

Upvotes: 2

Related Questions