From 93a6269287d9da0e640520b5770a52bc93492e69 Mon Sep 17 00:00:00 2001 From: patrickjieraldjuan Date: Sat, 10 Feb 2024 00:42:43 +0800 Subject: [PATCH] Updated add to cart controller --- controllers/productControllers.js | 67 +++++++++++++++++-------------- 1 file changed, 37 insertions(+), 30 deletions(-) diff --git a/controllers/productControllers.js b/controllers/productControllers.js index df12e8f..f02d65c 100644 --- a/controllers/productControllers.js +++ b/controllers/productControllers.js @@ -307,43 +307,50 @@ async function updateProductInventory(cartItems) { // My Cart exports.addProductToCart = async (req, res) => { - try { - const { productId, quantity } = req.body; + try { + const { productId, quantity } = req.body; - // Find the user - const user = await User.findById(req.user.id); + // Find the user + const user = await User.findById(req.user.id); - // Check if the cart array exists - if (!user.myCart) { - user.myCart = []; - } + // Check if the cart array exists + if (!user.myCart) { + user.myCart = []; + } - const existingItemIndex = user.myCart.findIndex(item => item.productId === productId); + // Check if the product already exists in the cart + const existingItemIndex = user.myCart.findIndex(item => item.productId === productId); - if (existingItemIndex !== -1) { - // Update quantity of existing item - user.myCart[existingItemIndex].quantity += quantity; - } else { - if (quantity <= 0) { - return res.json({ message: 'Provide valid quantity' }); - } - // Add new item to cart - const product = await Product.findById(productId); - user.myCart.push({ - productId, - name: product.name, - quantity - }); + if (existingItemIndex !== -1) { + // Update quantity of existing item + await User.findByIdAndUpdate( + req.user.id, + { + $inc: { [`myCart.${existingItemIndex}.quantity`]: quantity } // Increment the quantity field + }, + { new: true } // Return the updated user after the operation + ); + } else { + if (quantity <= 0) { + return res.json({ message: 'Provide valid quantity' }); } - + // Add new item to cart + const product = await Product.findById(productId); + user.myCart.push({ + productId, + name: product.name, + quantity + }); await user.save(); // Save the updated user with cart items - - res.json({ message: 'Product added to cart successfully' }); - } catch (error) { - console.error(error); - res.status(500).json({ message: 'Error adding product to cart' }); } - }; + + res.json({ message: 'Product added to cart successfully' }); + } catch (error) { + console.error(error); + res.status(500).json({ message: 'Error adding product to cart' }); + } +}; + exports.updateProductQuantity = async (req, res) => { try {