Updated add to cart controller

master
parent a3f1a510b6
commit 93a6269287

@ -318,11 +318,18 @@ exports.addProductToCart = async (req, res) => {
user.myCart = [];
}
// 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;
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' });
@ -334,16 +341,16 @@ exports.addProductToCart = async (req, res) => {
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' });
}
};
};
exports.updateProductQuantity = async (req, res) => {
try {

Loading…
Cancel
Save