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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…