Updated code for updateProductQuantity controller and route changed to POST

master
parent 43bcc01072
commit 063155a7a5

@ -356,36 +356,36 @@ exports.updateProductQuantity = async (req, res) => {
try {
const { productId, quantity } = req.body;
// Find the user
const user = await User.findById(req.user.id);
if (!user.myCart) {
return res.status(400).json({ message: 'Cart is empty' });
}
const itemIndex = user.myCart.findIndex(item => item.productId === productId);
if (itemIndex === -1) {
return res.status(404).json({ message: 'Product not found in cart' });
}
// Validate quantity (e.g., must be positive, not exceed available inventory)
if (quantity <= 0) {
return res.status(400).json({ message: 'Quantity must be greater than zero' });
}
// Update quantity in the cart
user.myCart[itemIndex].quantity = quantity;
// Update quantity in the cart using findByIdAndUpdate
const updatedUser = await User.findByIdAndUpdate(
req.user.id,
{ $set: { 'myCart.$[element].quantity': quantity } },
{
new: true, // return the updated document
arrayFilters: [{ 'element.productId': productId }] // update the element where productId matches
}
);
if (!updatedUser) {
return res.status(404).json({ message: 'User not found' });
}
await user.save(); // Save the updated cart
if (!updatedUser.myCart) {
return res.status(400).json({ message: 'Cart is empty' });
}
res.json({ message: 'Product quantity updated successfully' });
console.log(user.myCart);
res.json({ message: 'Product quantity updated successfully', updatedCart: updatedUser.myCart });
} catch (error) {
console.error(error);
res.status(500).json({ message: 'Error updating product quantity' });
}
};
};
exports.removeProductFromCart = async (req, res) => {
try {

@ -44,7 +44,7 @@ router.post('/getProductName', productControllers.getProductName);
// My Cart
router.post('/add-to-cart', verify, verifyNonAdmin, productControllers.addProductToCart);
router.put('/update-quantity', productControllers.updateProductQuantity);
router.post('/update-quantity', verify, verifyNonAdmin, productControllers.updateProductQuantity);
router.delete('/remove/:productId', verify, verifyNonAdmin, productControllers.removeProductFromCart);
router.post('/view-my-cart', verify, verifyNonAdmin, productControllers.getCartDetails);

Loading…
Cancel
Save