Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove a object from array using MongoDB

I am trying to remove a product from the user's cart when I delete it from the web, but I don't know how to do it.

The moongoose schema of User is the following:

var schema = mongoose.Schema({
      email: { type: String, required: true },
      password: { type: String, required: true },
      name: { type: String, required: true },
      surname: { type: String, required: true },
      address: { type: String, required: true },
      birth: { type: Date, required: true },
      cartItems: {
          type: [{
              qty: { type: Number, required: true },
              product: { type: mongoose.Schema.Types.ObjectId, ref: 'Product' }
          }]
      }
});

I want to remove an item from cartItems. How can I do it?

like image 267
Rioichi Avatar asked Jun 12 '26 19:06

Rioichi


1 Answers

db.collection.update(
  { _id: id },
  { $pull: { 'cartItems.type': { product: '....' } } }
);

more about $pull

like image 60
sandeep.kgp Avatar answered Jun 14 '26 08:06

sandeep.kgp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!