Я делаю кондитерскую, где пользователь может добавить торт в корзину. Находясь в тележке, они могут изменить размер торта на любой желаемый. При изменении размера торта цена меняется и сохраняется в сеансе
![enter image description here](https://i.stack.imgur.com/j4fUK.png)
Я понял, что если пользователь добавляет тот же торт в корзину, он отменяет один добавлен ранее.
Это не то, что я хочу, так как я хотел бы добавить новый торт в корзину, если размер торта, который сейчас находится в корзине, не тот.
Я сохраняю корзину в сеансе на основе этой модели:
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
});
}
I поймите, что это происходит из-за id. Но есть ли способ проверить размер торта?