Kindly wait a moment, post will be visible in just 5 seconds.

No Preview

Minhajur Rohoman

Posted on 13 August 2022

Updating the path 'cartItems.$' would create a conflict at 'cartItems'

Ad Banner
No Preview

const Cart = require(../models/cart);
function runUpdate(condition, updateData) {
return new Promise((resolve, reject) => {
//you update code here
Cart.findOneAndUpdate(condition, updateData, { upsert: true })
.then((result) => {
resolve();
})
.catch((err) => reject(err));
});
}
exports.addItemToCart = async (req, res) => {
console.log(Req from body, req.body);
await Cart.findOne({ user: req.user._id }).exec((error, cart) => {
console.log(cart);
if (error) {
return res.status(400).json({ error });
}
if (cart) {
//if cart already exists then update cart by quantity
let promiseArray = [];

req.body.cartItems.map((cartItem) => {
const product = cartItem.product;
const item = cart.cartItems.find((c) => c.product == product);
let condition, update;
if (item) {
condition = { user: req.user._id, cartItems.product: product };
update = {
$set: {
cartItems.$: cartItem,
},
};
} else {
condition = { user: req.user._id };
update = {
$push: {
cartItems: cartItem,
},
};
}
promiseArray.push(runUpdate(condition, update));
});
Promise.all(promiseArray)
.then((response) => res.status(201).json({ response }))
.catch((error) => {
console.log(error);
res.status(400).json({ error });
});
} else {
//if cart not exist then create a new cart
const cart = new Cart({
user: req.user._id,
cartItems: req.body.cartItems,
});
cart.save((error, cart) => {
if (error) return res.status(400).json({ error });
if (cart) {
return res.status(201).json({ cart });
}
});
}
});
};
exports.getCartItems = (req, res) => {
Cart.findOne({ user: req.user._id })
.populate(cartItems.product, _id name price productPictures)
.exec((error, cart) => {
if (error) return res.status(400).json({ error });
if (cart) {
let cartItems = {};
cart.cartItems.forEach((item, index) => {
cartItems[item.product._id.toString()] = {
_id: item.product._id.toString(),
name: item.product.name,
img: item.product.productPictures[0].img,
price: item.product.price,
qty: item.quantity,
};
});
res.status(200).json({ cartItems });
}
});
//}
};

I couldn't find the problem! what is going on?

0

48

0

No Preview

Minhajur Rohoman

Explore more similar Post

0 Comments

Loading..