|
|
|
@ -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,9 +341,8 @@ 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) {
|
|
|
|
@ -345,6 +351,7 @@ exports.addProductToCart = async (req, res) => {
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
exports.updateProductQuantity = async (req, res) => {
|
|
|
|
|
try {
|
|
|
|
|
const { productId, quantity } = req.body;
|
|
|
|
|