Search code examples
node.jsmongodbmongoose-schemamongodb-update

How can i update the product quantity in cart?


My cart schema

var CartSchema = new mongoose.Schema({
    product: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Product'
    },
    totalQty: {
        type: Number,
        default: 0
    },
    totalPrice: {
        type: Number,
        default: 0
    },
    user:{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    },
    items : Array,
    orderedQty: Number
});

After inserting one record I have got the response

{
    "totalQty": 1,
    "totalPrice": 6500,
    "items": [
        {
            "qty": 1,
            "item": {
                "_id": "5b28d30888afb703508409bb",
                "name": "LENOVO VIBE K5",
                "price": 6500,
                "quantity": 15,
                "imagePath": "https://in.bmscdn.com/showcaseimage/eventimage/hereditary-17-06-2018-10-06-45-907.jpg",
                "description": "This is showcase image from bms",
                "__v": 0
            },
            "price": 6500
        }
    ],
    "_id": "5b2a3da1f4fd65265c8ab477",
    "user": "5b27898931169e074c2dc228",
    "__v": 0
}

I want to update the "qty" inside the items[] array. How can I write the update query?


Solution

  • Use the $inc operator:

    db.cart.update(
        {_id: ObjectId('5b2a3da1f4fd65265c8ab477'), 'items.item._id': ObjectId('5b28d30888afb703508409bb')},
        {$inc: {"items.$.qty": value}} // Pass your increase value here
    )