【发布时间】:2021-12-03 15:59:13
【问题描述】:
我有一个购物车。在模式的当前状态下,其中包含的每个元素都由 Products 数组中的一个对象表示。对该函数的每次调用都会删除等于 1 的通过其 itemId 传递的对象的数量。当我想删除数量等于 1 的对象(因此数量值达到 0)时,我想从 Products 数组中删除购物车中的对象(因此 itemId 和数量)。如果大于 1,则只有减少数量的值时才起作用,而不是消除产品编号时,会显示消息'Deleted item in cart。但事实并非如此,它仍然存在于数据库中
购物车架构
const mongoose = require('mongoose');
const idValidator = require('mongoose-id-validator');
const Schema = mongoose.Schema;
const cartSchema = new Schema ({
products: [
{
productId: { type: mongoose.Types.ObjectId, required: true, ref: 'Product' },
quantity: { type: Number, required: true },
}
],
customer: { type: mongoose.Types.ObjectId, required: true, unique: true, ref: 'User'}
});
cartSchema.plugin(idValidator);
module.exports = mongoose.model('Cart', cartSchema);
函数减少
const removeToCartByUserId = async (req, res, next) => {
const userId = req.params.uid;
const { productId } = req.body;
const quantity = 1;
try {
let cart = await Cart.findOne({customer: userId});
//Cart exist for user
if(cart) {
let itemIndex = cart.products.findIndex(p => p.productId == productId);
//product exists in the cart, update the quantity
if (itemIndex > -1) {
let productItem = cart.products[itemIndex];
if(productItem.quantity > 1) {
productItem.quantity -= quantity;
cart = await cart.save();
res.status(201).json({ cart });
} else { // delete product in array
await cart.products.pull({ productId: productId }) // removed
cart = await cart.save();
res.status(200).json({ message: 'Deleted item in cart.' });
}
}
} else { // no Cart for the user, exit
const error = new HttpError('Something went wrong with the cart.', 500);
return next(error);
}
} catch(err) {
console.log(err);
const error = new HttpError('Something went wrong with the cart.', 500);
return next(error);
}
};
更新: 我编辑了代码,现在它可以工作了
//product exists in the cart, update the quantity
if (itemIndex > -1) {
let productItem = cart.products[itemIndex];
productItem.quantity -= quantity;
if(productItem.quantity > 0) {
cart = await cart.save();
res.status(201).json({ cart });
} else { // delete product in array
await Cart.updateOne(
{ itemIndex },
{$pull : { "products": { productId } } }
);
res.status(200).json({ message: 'Deleted item in cart.' });
}
}
【问题讨论】: