Reputation: 1841
I have a Node/Express API using Mongoose, where I am trying to update subdocuments within multiple documents.
Essentially I have a user with a profile that has multiple phone numbers that they can share with another contact.
Each contact has a profile.contacts[] section, that has profile.contacts.phones[] section.
When the main user sharing his/her phone number with other users changes his/her number, I want to update the profile.contacts.phones[] section in all documents, where the _id of that phone number matches.
Here is my code:
Profile.update({'contacts.phones._id':req.body._id}, {
Profile.contacts.phones.phone_number:req,body.phone_number,
Profile.contacts.phones.phone_type:req.body.phone_type
}, {multi:true}, function(err, result){
if(err)
res.send(err)
res.json(result);
})
Here is a sample "Profile" document:
{
"_id" : ObjectId("59c09dca981de33d180df943"),
"last_name" : "Sam",
"first_name" : "Sam",
"owner_id" : "59c09dca981de33d180df940",
"contacts" : [
{
"first_name" : "Joe",
"last_name" : "Public",
"_id" : ObjectId("59c09dca981de33d180df944"),
"phones" : [
{
"phone_number" : "2067155803",
"phone_type" : "home",
"_id" : ObjectId("59bca0b55481370985cac29a")
}
]
}
]
"__v" : 0
}
Based on what I see in the documentation, this should work...
Thanks for any insight!!
Upvotes: 0
Views: 175
Reputation: 12089
I think you would need to use the positional operator to update an object in an array $ that matched the query.
However, this cannot be used for nested arrays:
The positional $ operator cannot be used for queries which traverse more than one array, such as queries that traverse arrays nested within other arrays, because the replacement for the $ placeholder is a single value.
https://docs.mongodb.com/manual/reference/operator/update/positional/
You might have to consider restructuring your documents.
Upvotes: 1