Javascript 如何将不同尺寸的同一产品作为单独项目添加到购物车中?
我正在做一个蛋糕店,用户可以添加一个蛋糕到购物车。在购物车中,他们可以根据自己的需要改变蛋糕的大小。更改蛋糕大小时,价格会发生变化并存储在会话中Javascript 如何将不同尺寸的同一产品作为单独项目添加到购物车中?,javascript,node.js,mongodb,session,ejs,Javascript,Node.js,Mongodb,Session,Ejs,我正在做一个蛋糕店,用户可以添加一个蛋糕到购物车。在购物车中,他们可以根据自己的需要改变蛋糕的大小。更改蛋糕大小时,价格会发生变化并存储在会话中 我意识到,如果用户将相同的蛋糕添加到购物车中,它将覆盖先前添加的蛋糕。 这不是我想要的,因为如果当前在购物车中的蛋糕大小不一样,我想在购物车中添加一个新的蛋糕 我将购物车存储在基于此模型的会话中: module.exports = function Cart(oldCart) { // If there's no cart in the s
我意识到,如果用户将相同的蛋糕添加到购物车中,它将覆盖先前添加的蛋糕。
这不是我想要的,因为如果当前在购物车中的蛋糕大小不一样,我想在购物车中添加一个新的蛋糕 我将购物车存储在基于此模型的会话中:
module.exports = function Cart(oldCart) {
// If there's no cart in the session, create a new empty object
this.items = oldCart.items || {};
this.totalQty = oldCart.totalQty || 0;
this.totalPrice = oldCart.totalPrice || 0;
//item will be an object based on a document from MongoDB
//id is the unique _id from the item
this.add = function(item, id) {
let storedItem = this.items[id];
//If the item is not on the cart, add it
if(!storedItem){
storedItem = this.items[id] = {item: item, qty: 0, price: 0, cakesize: '1kg', singlePrice: 0}
}
//If the cart is on the cart, increment its quantity and price
storedItem.qty ++;
storedItem.price = storedItem.item.price['1000'] * storedItem.qty;
//Total of all items in the cart
this.totalQty++;
this.totalPrice += storedItem.item.price['1000'];
}
//Function to create an array
this.generateArray = function() {
let arr = [];
for (var id in this.items) {
arr.push(this.items[id]);
}
return arr;
}
};
要渲染视图的控制器
exports.getShoppingCart = (req,res,next) => {
if(!req.session.cart) {
return res.render("shop/cart", {
path: "/cart",
cakes: null
});
}
let cart = new Cart(req.session.cart);
res.render("shop/cart", {
path: "/cart",
cakes: cart.generateArray(),
totalPrice: cart.totalPrice
});
}
我知道这是由于id造成的。但是有没有办法检查蛋糕大小呢?正如@Sergio在上面的评论中建议的那样,在创建购物车id时,我在id的末尾添加了cakesize:
cakeId+size
。正如@Sergio在上面的评论中建议的那样,在创建购物车id时,我在id的末尾添加了cakesize:cakeId+size
。这就成功了也许你可以创建购物车id,比如cakeID+size
这就成功了。很多感谢您可能会创建购物车id,如cakeID+size
这就成功了。非常感谢