Updated add to cart controller

master
parent a3f1a510b6
commit 93a6269287

@ -318,11 +318,18 @@ exports.addProductToCart = async (req, res) => {
user.myCart = []; user.myCart = [];
} }
// Check if the product already exists in the cart
const existingItemIndex = user.myCart.findIndex(item => item.productId === productId); const existingItemIndex = user.myCart.findIndex(item => item.productId === productId);
if (existingItemIndex !== -1) { if (existingItemIndex !== -1) {
// Update quantity of existing item // 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 { } else {
if (quantity <= 0) { if (quantity <= 0) {
return res.json({ message: 'Provide valid quantity' }); return res.json({ message: 'Provide valid quantity' });
@ -334,9 +341,8 @@ exports.addProductToCart = async (req, res) => {
name: product.name, name: product.name,
quantity quantity
}); });
}
await user.save(); // Save the updated user with cart items await user.save(); // Save the updated user with cart items
}
res.json({ message: 'Product added to cart successfully' }); res.json({ message: 'Product added to cart successfully' });
} catch (error) { } catch (error) {
@ -345,6 +351,7 @@ exports.addProductToCart = async (req, res) => {
} }
}; };
exports.updateProductQuantity = async (req, res) => { exports.updateProductQuantity = async (req, res) => {
try { try {
const { productId, quantity } = req.body; const { productId, quantity } = req.body;

Loading…
Cancel
Save