Updated codes for removeProductsFromCart controller and route changed using params to only using req body

master
parent 063155a7a5
commit 6f03dc9179

@ -387,31 +387,33 @@ exports.updateProductQuantity = async (req, res) => {
}; };
exports.removeProductFromCart = async (req, res) => { exports.removeProductsFromCart = async (req, res) => {
try { 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 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, req.user.id,
{ {
$pull: { myCart: { productId } } $pull: { myCart: { productId: { $in: productIds } } }
}, },
{ new: true } // Return the updated user document { new: true }
).exec(); ).exec();
if (existingItemIndex <= 0) { // Check if any products were removed from the cart
res.json({ message: 'Product not in cart' }); if (updatedUser) {
res.json({ message: 'Products removed from cart successfully' });
} else { } else {
res.json({ message: 'Product removed from cart successfully' }); res.status(404).json({ message: 'No products removed from cart' });
} }
} catch (error) { } catch (error) {
console.error(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) => { exports.getCartDetails = async (req, res) => {
try { try {
const user = await User.findById(req.user.id); const user = await User.findById(req.user.id);

@ -45,7 +45,7 @@ router.post('/getProductName', productControllers.getProductName);
router.post('/add-to-cart', verify, verifyNonAdmin, productControllers.addProductToCart); router.post('/add-to-cart', verify, verifyNonAdmin, productControllers.addProductToCart);
router.post('/update-quantity', verify, verifyNonAdmin, productControllers.updateProductQuantity); 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); router.post('/view-my-cart', verify, verifyNonAdmin, productControllers.getCartDetails);

Loading…
Cancel
Save