Home > OS >  How to increment a field inside the array of documents in mongo Db?
How to increment a field inside the array of documents in mongo Db?

Time:10-01

I want to increment the quantity field inside the products array of the cart when the productId matches to the itemid. Also I want to get the updated document in return.

Here is my Cart Model

import mongoose from 'mongoose';

const cartSchema = new mongoose.Schema({
    userId: {
        type: String,
        required: true,
    },
    products: [
        {
            productId: {
                type: String,
            },
            quantity: {
                type: Number,
                default: 1
            }
        }

    ]
    
}, {timestamps: true});
const Cart = new mongoose.model('Cart', cartSchema);

export default Cart;

and here is what I m doing:

const updatedCart = await Cart.findOneAndUpdate({"products.productId": itemid}, {$inc: {quantity: 1}}, {new: true})

//console.log(updatedCart)

But an empty array return and also quantity didn't increment.

CodePudding user response:

As from your schema, there is no quantity field. Hence your mongoose operation is not updating any document.

Hence it will not return any document as new: true only returns the updated document.

[options.returnOriginal=null] «Boolean» An alias for the new option. returnOriginal: false is equivalent to new: true.


You can use positional $ operator to update the quantity of filtered product in products array.

The positional $ operator identifies an element in an array to update without explicitly specifying the position of the element in the array.

const updatedCart = await Cart.findOneAndUpdate({ "products.productId": itemid },
  { $inc: { "products.$.quantity": 1 } }, 
  { new: true });

Sample Mongo Playground

  • Related