Pranay kumar
Pranay kumar

Reputation: 2197

deleting an object from array in mongo collection

I have a mongo schema like this.

{
 userID:19202,
 products:[ { id:020, name:'first'  }]
}

I want to pop items from the product array based on id. I used the following command. although it didn't give any error, it also not deleting elements from an array.

 userCart.updateOne(
                { userID:userID},
                { $pull: { products: { id:id } } }
              )
             .then((data) =>
             {
                 if(data)
                 {

 //data is {
        "n": 1,
        "nModified": 0,
        "ok": 1
    }
                     return res.json({
                         status:true,
                         message:"cart updated"
                     })
                 }
             })

Upvotes: 0

Views: 41

Answers (2)

abrorkhamidov
abrorkhamidov

Reputation: 143

Try this one:

db.userCart.update(
  { userID:userID }, 
  { $pull: { items: { id: 020 } } },
  false, // Upsert
  true, // Multi
);

Upvotes: 0

Demo - https://mongoplayground.net/p/mh6fXN21vyR

Make sure id and products.id are of the same type as in your document in the database. As your sample, both should be numbers.

if they both are number

db.collection.update({
  userID: 19202
},
{
  $pull: {
    "products": { id: 20 }
  }
})

Not Working here - https://mongoplayground.net/p/3zhv8yoH2o9 when "products": { id: "20" }. products.id is a string in the mongo query and in the database in number so mismatched.

Upvotes: 2

Related Questions