如何将购物车商品数量减一

时间:2021-01-04 11:17:20

标签: node.js express

我一直在尝试创建一个购物车,我可以在其中减少购物车中商品的数量,但我不知道该怎么做,也不知道如何使用邮递员对其进行测试。这是迄今为止已实施的内容。我需要减少数量,例如,如果用户从 3 件商品更改为 2 件商品,我想将数量减少 1,并将价格和总数更改为当前数量

let { productId } = req.body;
const quantity = Number.parseInt(req.body.quantity);

let productObject = await Products.findOne({ _id: productId });
let cartObject = await CartItem.findOne({ status: 1 });
let productPriceObject = await Price.findOne({ productId: productObject._id, status: 1 });

if (cartObject.items.unitCount <= quantity) {
    var oldQuantity = 0;

    for (var i = 0; i < cartObject.items.length; i++) {
        if (cartObject.items[i]._id == productId) {
            oldQuantity = cartObject.items[i].unitCount;
        }
    }

    let cartUpdateObject = await CartItem.findOneAndUpdate({
        _id: cartObject._id,
        productId: items.productId,
        status: 1,
        guestId: req.guest._id,
    }, { $set: { "items.$.unitCount": quantity } }, { new: true });

    if (!!cartUpdateObject) {

        cartObject.items[i].total = cartObject.items[i].unitCount * productPriceObject.value;
        cartObject.items[i].price = productPriceObject.value;
        cartObject.subTotal = cartObject.items.map((item) => item.total).reduce((acc, next) => acc + next);

    } else {
        return res.status(400)
            .json({
                success: false,
                message: "unable to update quantity",
                error,
            });
    }
}

这是我用于创建购物车项目的购物车模型的架构模型

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

let ItemSchema = new Schema({
    productId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Product",
    },
    unitCount: {
        type: Number,
        required: true,
        min: [1, 'Quantity can not be less then 1.']
    },
    price: {
        type: Number,
        required: true
    },
    total: {
        type: Number,
        required: true,
    }
}, {
    timestamps: true
})
module.exports = mongoose.model('item', ItemSchema);

const CartSchema = new Schema({
    userId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "User",
    },

    items: [ItemSchema],

    subTotal: {
        default: 0,
        type: Number
    }
}, {
    timestamps: true
})
module.exports = mongoose.model('cart', CartSchema);

0 个答案:

没有答案