Search code examples
javascriptarraysmongodbobjectmongoose

mongodb will keep creating a new cart instead of using the previously created cart How do I fix this?


I am trying to add a product to a shopping cart in mongodb but the code I have written does not work. It was previously working but when I switched from local mongodb to mongodb atlas cloud and then back to local mongodb it started having issues because it will not use the cart that gets created when redirected to '/' root and instead will keep creating a new cart with a new req.session.cartId belonging to it each time a product is added to cart. I have had so many issues with this one section and it is the final part of my project to get working before live hosting. Any help is appreciated. thank you.

const express = require('express');
const Carts = require('../repo/carts');
const Product = require('../repo/products');
const cartShowTemplate = require('../views/carts/show');

const router = express.Router();
let cart;

router.post('/cart/products', async (req, res) => {
  try {
    cart = await Carts.findById(req.session.cartId);
    // Check if cart exists
    if (!cart) {
      // Create new cart
      cart = await Carts.create({
        _id: req.session.cartId,
        items: [],
      });
    }

    // Check if product is present
    const productIndex = cart.items.findIndex(
      (item) => item._id === req.body.productId
    );
    if (productIndex === -1) {
      // Create new product
      cart.items.push({
        _id: req.body.productId,
        quantity: 1,
      });
    } else {
      // Update existing product
      cart.items[productIndex].quantity += 1;
    }

    // Save updated cart
    await cart.save();
    console.log(cart);
    res.status(200).send('product added to cart!!');
  } catch (err) {
    res.status(500).send('there was an error');
  }
});
        module.exports = router;

example of the array
the correct product gets added but a new cart with a new id gets created each time instead of using the same cart. I am not sure if this helps but what I noticed when I console.log(req.sessionID) it will show the same ID each time its console.logged but when console.logging (req.session.cartId) that will show as undefined when before it was showing an id.

enter image description here

carts schema

const mongoose = require('mongoose');

const cartSchema = new mongoose.Schema({
  _id: String,
  items: [
    { quantity: Number, _id: String }
  ]
});

const Carts = new mongoose.model('Carts', cartSchema);

module.exports = Carts;

Solution

  • Try with this logic:

    router.post('/cart/products', async (req, res) => {
      try {
        let cart = await Carts.findById(req.session.cartId);
        // Check if cart exists
        if (!cart) {
          // Create new cart
          cart = await Carts.create({
            _id: req.session.cartId,
            items: [],
          });
        }
    
        // Check if product is present
        const productIndex = cart.items.findIndex(
          (item) => item._id === req.body.productId
        );
        if (productIndex === -1) {
          // Create new product
          cart.items.push({
            _id: req.body.productId,
            quantity: 1,
          });
        } else {
          // Update existing product
          cart.items[productIndex].quantity += 1;
        }
    
        // Save updated cart
        await cart.save();
    
        res.status(200).send('product added to cart!!');
      } catch (err) {
        res.status(500).send('there was an error');
      }
    });