From 6f03dc9179ed95355d60b97444adbf49c79beba2 Mon Sep 17 00:00:00 2001 From: patrickjieraldjuan Date: Sat, 10 Feb 2024 21:01:50 +0800 Subject: [PATCH] Updated codes for removeProductsFromCart controller and route changed using params to only using req body --- controllers/productControllers.js | 26 ++++++++++++++------------ routes/productRoutes.js | 2 +- 2 files changed, 15 insertions(+), 13 deletions(-) diff --git a/controllers/productControllers.js b/controllers/productControllers.js index f84969e..9dfaf95 100644 --- a/controllers/productControllers.js +++ b/controllers/productControllers.js @@ -387,31 +387,33 @@ exports.updateProductQuantity = async (req, res) => { }; -exports.removeProductFromCart = async (req, res) => { +exports.removeProductsFromCart = async (req, res) => { try { - const productId = req.params.productId; + const productIds = req.body.productIds; // Array of product IDs to remove const user = await User.findById(req.user.id); - const existingItemIndex = user.myCart.findIndex(item => item.productId === productId); - let x = await User.findByIdAndUpdate( + // Update the user's cart by removing the products with the given IDs + const updatedUser = await User.findByIdAndUpdate( req.user.id, { - $pull: { myCart: { productId } } + $pull: { myCart: { productId: { $in: productIds } } } }, - { new: true } // Return the updated user document + { new: true } ).exec(); - if (existingItemIndex <= 0) { - res.json({ message: 'Product not in cart' }); - }else{ - res.json({ message: 'Product removed from cart successfully' }); - } + // Check if any products were removed from the cart + if (updatedUser) { + res.json({ message: 'Products removed from cart successfully' }); + } else { + res.status(404).json({ message: 'No products removed from cart' }); + } } catch (error) { console.error(error); - res.status(500).json({ message: 'Error removing product from cart' }); + res.status(500).json({ message: 'Error removing products from cart' }); } }; + exports.getCartDetails = async (req, res) => { try { const user = await User.findById(req.user.id); diff --git a/routes/productRoutes.js b/routes/productRoutes.js index 61fec60..6cb1109 100644 --- a/routes/productRoutes.js +++ b/routes/productRoutes.js @@ -45,7 +45,7 @@ router.post('/getProductName', productControllers.getProductName); router.post('/add-to-cart', verify, verifyNonAdmin, productControllers.addProductToCart); router.post('/update-quantity', verify, verifyNonAdmin, productControllers.updateProductQuantity); -router.delete('/remove/:productId', verify, verifyNonAdmin, productControllers.removeProductFromCart); +router.delete('/remove', verify, verifyNonAdmin, productControllers.removeProductsFromCart); router.post('/view-my-cart', verify, verifyNonAdmin, productControllers.getCartDetails);