HungryBird
HungryBird

Reputation: 95

I want to update sub document in array

I now use mongooses to pull and pull subdocuments to the array, and now I want to change the contents of the detail field of that subdocument with the _id of the subdocument.

{
    subDocument: [{
        _id: ObjectId('123'),
        detail: 'I want update this part'          
    }]
}

I tried to use the $set method as shown below but it did not work as expected.

Model.findByIdAndUpdate(uid, { $Set: {subDocument: {_id: _id}}});

Looking at the for statement as shown below is likely to have a bad effect on performance. So I want to avoid this method.

const data = findById(uid);

for(...) {
    if(data.subDocument[i]._id==_id) {
        data.subDocument[i].detail = detail
    }
}

Can you tell me some mongodb queries that I can implement?

And, Is it not better to use the 'for(;;)' statement shown above than to search using mongodb's query?

Upvotes: 0

Views: 138

Answers (2)

Sparw
Sparw

Reputation: 2743

To find subdocument by id, I am using something like this :

var subDocument = data.subDocument.id(subDocumentId);
if (subDocument) {
  // Do some stuff
}
else {
  // No subDocument found
}

Hope it helps.

Upvotes: 1

wrangler
wrangler

Reputation: 3576

This should work:

Model.findOneAndUpdate({"subdocument._id": uid},
        {
           $set: {
                "subdocument.$.detail ": "detail here"
            }
         },
        ).exec(function(err, doc) {
               //code 
        });

Upvotes: 1

Related Questions