如何更新购物车中的产品数量?

时间:2018-06-20 12:41:32

标签: node.js mongodb mongoose-schema mongodb-update

我的购物车模式

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
});

插入一条记录后,我得到了答复

{
    "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
}

我想更新items []数组内的“数量”。如何编写更新查询?

1 个答案:

答案 0 :(得分:1)

使用$inc运算符:

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