Updated add to cart controller

master
parent a3f1a510b6
commit 93a6269287

@ -307,43 +307,50 @@ async function updateProductInventory(cartItems) {
// My Cart
exports.addProductToCart = async (req, res) => {
try {
const { productId, quantity } = req.body;
try {
const { productId, quantity } = req.body;
// Find the user
const user = await User.findById(req.user.id);
// Find the user
const user = await User.findById(req.user.id);
// Check if the cart array exists
if (!user.myCart) {
user.myCart = [];
}
// Check if the cart array exists
if (!user.myCart) {
user.myCart = [];
}
const existingItemIndex = user.myCart.findIndex(item => item.productId === productId);
// 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;
} else {
if (quantity <= 0) {
return res.json({ message: 'Provide valid quantity' });
}
// Add new item to cart
const product = await Product.findById(productId);
user.myCart.push({
productId,
name: product.name,
quantity
});
if (existingItemIndex !== -1) {
// Update quantity of existing item
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' });
}
// Add new item to cart
const product = await Product.findById(productId);
user.myCart.push({
productId,
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' });
}
};
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