简体   繁体   中英

How to add the same product with different sizes to the shopping cart as a separate item?

I am making a cake shop where a user can add a cake to Cart. While in the cart, they can change the cake size to what that they want. On changing the cake size, the price changes and gets stored in the session
在此处输入图像描述

I realized that if the user adds the same cake to the cart, it overrides the one previously added.
This is not what I want, as I'd like to add a new cake to the cart if the cake size of the cake currently in the cart is not the same.

I'm storing the cart in a session based on this model:

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

};

The controller to render view

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 understand that this is happening due to the id. But is there a way to check for the cake size as well?

As advised by @Sergio in a comment above, On creating the shopping cart id, I added the cakesize to the end of the id: cakeId + size . That did the trick

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM