0
ProductCollection: 
{
  _id: { ObjectId('x1')},
  products: [ 
              { listPrice: '1.90', product: {id: 'xxx1'} },
              { listPrice: '3.90', product: {id: 'xxx2'} },
              { listPrice: '5.90', product: {id: 'xxx3'} }
            ]
},
{
  _id: { ObjectId('x2')},
  products: [ 
              { listPrice: '2.90', product: {id: 'xxx4'} },
              { listPrice: '4.90', product: {id: 'xxx5'} },
              { listPrice: '5.90', product: {id: 'xxx6'} }
            ]
},

I want to remove subdocument (xxx3) from collection (x1), and try below:

ProductCollection.update(
{ 
  "_id": mongoose.Types.ObjectId('x1')  
}, 
{ 
  $pull : { 'products.product': {id: 'xxx3' } } 
} 

It just doesn't seem to work. Can anyone please help me? Thank you

3
  • It should be { $pull : { 'products': { 'product.id': 'xxx3' } } } Commented Feb 9, 2019 at 7:01
  • @Winzlet: I tried (seems similar to kmreko advise below, except with quote for 'products'). It gave same result and throws me this error: UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "xxx1" at path "product". Next, I tried also: $pull : { 'products': { 'product._id': mongoose.Types.ObjectId('5baa131b36d6a02b442b4b5e') } }. There is no error this time, but nothing happen. The subdocument is still there, anything went wrong here? Thank you Commented Feb 9, 2019 at 7:52
  • @Winzlet: Same advise to above, I switch to match to '_id' using this code: $pull : { products: { 'product': { 5baa131b36d6a02b442b4b5e } } }. It works perfectly. Thank you Commented Feb 9, 2019 at 9:22

2 Answers 2

6

The field for $pull needs to be the array.

This should work:

$pull: { products: { 'product.id': 'xxx3' } }
Sign up to request clarification or add additional context in comments.

2 Comments

I tried, but it throws me this error: UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "xxx1" at path "product". Next, I tried also: $pull : { 'products': { 'product._id': mongoose.Types.ObjectId('5baa131b36d6a02b442b4b5e') } }. There is no error this time, but nothing happen. The subdocument is still there, anything went wrong here? Thank you
I think your advise is correct, and I switch to match to '_id' using this code: $pull : { products: { 'product': { 5baa131b36d6a02b442b4b5e } } }. It works perfectly. Thank you
0

add this _id: {id: false} while creating mongoose schema

for eg:

partners:[{
    name: { type: String, default: '' },
    logo: { type: mongoose.Schema.Types.Mixed, default: '' },
    _id: { id: false }
  }],

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.