Reputation: 40163
I would like to update a subdocument that was fetched using $elemMatch. I've found some posts online but so far I am not able to get it to work. This is what I have:
Schema:
var user = {
_id: ObjectId
addresses: [{
_id: ObjectId
street: String
}]
};
Code:
this.findOne({
'addresses._id': address_id
}, { 'occurrences': { $elemMatch: {
'_id': address_id
}}})
.exec(function(err, doc) {
if (doc) {
// Update the sub doc
doc.addresses[0].street = 'Blah';
doc.update({ 'addresses': { $elemMatch: { '_id': address_id }}}, { $set: {"addresses.$.street": doc.addresses[0].street }})
.exec(function(err, count) {
...
The above results in the address sub doc to be wiped out and a blank new one recreated. How can I save the doc/subdoc?
My goal is to be able to fetch a document (user) by subdocument (addresses) ID, modify that one matching address then save it.
Upvotes: 6
Views: 16544
Reputation: 312179
You can do this all with a single update
call on the model instead of fetching it first with findOne
:
User.update(
{'addresses._id': address_id},
{$set: {'addresses.$.street': 'Blah'}},
function(err, count) { ... });
This uses the positional $
operator in the $set
to target just the addresses
element that was matched in the query.
Upvotes: 18