|
|
@ -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,16 +341,16 @@ 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) {
|
|
|
|
console.error(error);
|
|
|
|
console.error(error);
|
|
|
|
res.status(500).json({ message: 'Error adding product to cart' });
|
|
|
|
res.status(500).json({ message: 'Error adding product to cart' });
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
exports.updateProductQuantity = async (req, res) => {
|
|
|
|
exports.updateProductQuantity = async (req, res) => {
|
|
|
|
try {
|
|
|
|
try {
|
|
|
|