0

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!!

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks Steve, but I'm getting the following error: "cannot use the part (contacts of contacts.phones.phone_type) to traverse the element { contacts:[ { first_name:"Joe", last_name:"Public", _id:ObjectId('59c09dca981de33d180df944') phones:[ { phone_number:"2067155803", phone_type:"home", _id:ObjectId('59bca0b55481370985cac29a') } ] } ] }
I think the problem lies with the nested arrays: contacts and then phones.
Thanks for your help Steve. I ended up breaking out the contacts into a separate document as you suggested.
No problem. Glad you got it sorted.
Hey Steve, If you have a chance, I have a related question... kind of. stackoverflow.com/questions/46348270/…. If you get a chance...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.