Updated add to cart controller

master
parent a3f1a510b6
commit 93a6269287

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

Loading…
Cancel
Save