[Fixed] Mongoose Cannot Update Instead Create A New Array

Issue

I cannot update my collection even without encountering any error. Can someone help?
Please I am troubleshooting this for like 3 hours now.

const product_id = req.body.cartItems.product_id;
      const item = cart.cartItems.find(c => c.product_id == product_id);
      if (item) {
        Cart.findOneAndUpdate({ "user": req.user._id, "cartItems.product_id" : product_id }, {
            "$set": {
              "cartItems.$":{
                ...req.body.cartItems.quantity,
                quantity: item.quantity + req.body.cartItems.quantity
              }
            }
          })
          .exec((error, _cart) => {
          if (error) return res.status(400).json({ error });
          if (_cart) {
            return res.status(201).json({ _cart });
          }
        });

The MODEL:

const mongoose = require('mongoose');

const cartSchema = new mongoose.Schema({
    user: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true},
    cartItems: [
        {
            product_id: { type: mongoose.Schema.Types.ObjectId, ref: 'Product', required: true}, // This foreign key to product _id
            quantity: {type: Number,required: true},
            price: {type: Number, required: true}
        }
    ]
}, {timestamps: true});

module.exports = mongoose.model('Cart', cartSchema);

Solution

You need to use the $[] operator to update all documents inside the cartItems array matching your filter criteria. This operator acts like a placeholder for all items in the array. Considering your coding it would be something like this:

Cart.findOneAndUpdate({ "user": req.user._id, "cartItems.product_id" : product_id }, {
        "$set": {
          "cartItems.$[].quantity": item.quantity + req.body.cartItems.quantity
        }
      }).exec(...)

Leave a Reply

(*) Required, Your email will not be published