I want to add a product in a list of products in a specific cart from the list of carts.
There is a separate cart for every user. (I am binding the cart with the userId). Inside the Cart, there is an array of products with productId and quantity. So when a user wants to add an item to the cart, the product should be added to the cart only when it's not already in the cart. otherwise, the quantity of that product should be incremented by 1 in the product array of that specific cart.
I have added the comments for help. I have tried different ways to access the product and then updating it, but none is working. here is my code
Here is the cart Model:
import mongoose from 'mongoose';
const cartSchema = new mongoose.Schema({
userId: {
type: String,
required: true,
},
products: [
{
productId: {
type: String,
},
quantity: {
type: Number,
default: 1
}
}
]
}, {timestamps: true});
const Cart = new mongoose.model('Cart', cartSchema);
export default Cart;
and here is the Cart Controller where I am trying to access the DB and update it.
import Cart from '../models/cart.js';
export const addToCart = async (req,res) =>{
const item = req.body;
itemid = item._id;
const id = req.user.id;
try {
const preCart = await Cart.findOne({id}) //To find if the user has any previous cart
if(preCart) {
const preItem = await Cart.findOne({"products.productId": itemid})//to find item if it exists already
if(preItem){
//here i want to update this preItem with the increment by 1
const updatedItem = Cart.findByIdAndUpdate(id, {"products.productId": itemid}
{quantity: quantity++}, {new: true})
//its not working
}else {
//push the new item by updating the product array of that specific cart
}
console.log(updatedItem);
}else { //to create the cart if there is no
const product = {productId: item._id, quantity: 1};
newCart = await new Cart({userId: user.id, products: [product]}).save()
}
res.status(200).json(newCart)
} catch (error) {
}
}
thanks