Exploring My Object
{
service: 'user',
isModerator: true,
isAdmin: true,
carts: [
{
_id: 5e1344dcd4c94a1554ae0191,
qty: 1,
product: 5e09e4e0fcda6f268cefef3f,
user: 5e0dda6d6853702038da60f0,
expireAt: 2020-01-06T14:31:56.708Z,
__v: 0
},
{
_id: 5e13455306a54b31fc71b371,
qty: 1,
product: 5e09e507fcda6f268cefef40,// object ID
user: 5e0dda6d6853702038da60f0,
expireAt: 2020-01-06T14:33:55.573Z,
__v: 0
},
],
The goal here is to determine if the carts array already contains a cart with a specific product that a user is attempting to add, in order to prevent duplication and instead increase the quantity of the existing one.
My Implementation
const itemId = req.body._id;
const userId = req.user._id;
const { qty } = req.body;
try {
const productItem = await Product.findById(itemId);
const userDetail = await User.findById(userId).populate({
path: 'carts',
});
const locatedResult = userDetail.carts.find((o) => {
console.log(typeof o.product) // returns object
console.log(typeof productItem._id); // returns object
return o.product === productItem._id
});
console.log(locatedResult); // returns undefined
if (locatedResult !== undefined) {
const foundCartItem = await Cart.findById(locatedResult._id);
foundCartItem.qty += qty;
await foundCartItem.save();
return res.json({ message: 1 });
}
const newShoppingCart = new Cart({
qty,
product: productItem,
user: userDetail,
});
const cartAdded = await newShoppingCart.save();
userDetail.carts.push(cartAdded);
await userDetail.save();
return res.json({ message: 1 });
} catch (error) {
return console.log(error);
}