1

I have a model that looks like this:

contacts: {
  phones: [{
    phone_id: {
      type: ObjectId
    },
    phone_number: {
      type: String
    }
  }],
  shared: {
    phones: [{
      phone_id: {
        type: ObjectId
      },
      phone_number: {
        type: String
      },
    }]
  }
}

I have an endpoint, where I am trying to delete phone numbers matching an id I pass in my query string.

My code looks like this:

  Contacts.update({ 'phones._id': req.params.phone_id }, 
    { "$pull": { "phones": { "_id": req.params.phone_id} }}, 
    { safe: true, multi:true }, function(err, obj) {
  });

  Contacts.update({ 'shared.phones._id': req.params.phone_id }, 
    { "$pull": { "shared.phones": { "_id": req.params.phone_id} }}, 
    { safe: true, multi:true }, function(err, obj) {
  });

The first update that removes the number form the phones array works.

But the second that should remove the number from the 'shared.phones' array does not.

Any idea on what I'm missing?

I tried using the '$' positioning operator like this:

  Contacts.update({ 'shared.phones.$._id': req.params.phone_id }, 
    { "$pull": { "shared.phones.$": { "_id": req.params.phone_id} }}, 
    { safe: true, multi:true }, function(err, obj) {
  });

But that didn't work as well.

Thanks in advance!

2
  • try with { $pull: { 'shared.phones._id': req.params.phone_id } } Commented Nov 23, 2017 at 15:58
  • 1
    Thanks, Gregory! That was it. Commented Nov 23, 2017 at 17:27

1 Answer 1

1

As said in a comments

{ $pull: { 'shared.phones._id': req.params.phone_id } }

When it comes to nested array, always use all in one keys, because mongodb do not like to go in more than one level deep.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.