Rioichi
Rioichi

Reputation: 31

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?

Upvotes: 3

Views: 38

Answers (1)

sandeep.kgp
sandeep.kgp

Reputation: 886

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

more about $pull

Upvotes: 2

Related Questions