Quiero agregar un producto en una lista de productos en un carrito específico de la lista de carritos.
Hay un carro separado para cada usuario. (Estoy vinculando el carrito con el ID de usuario). Dentro del carrito, hay una variedad de productos con productId y cantidad. Entonces, cuando un usuario desea agregar un artículo al carrito, el producto debe agregarse al carrito solo cuando aún no está en el carrito. de lo contrario, la cantidad de ese producto debe incrementarse en 1 en la matriz de productos de ese carrito específico.
He agregado los comentarios para obtener ayuda. He intentado diferentes formas de acceder al producto y luego actualizarlo, pero ninguna funciona. aquí está mi código
Aquí está el modelo de carro:
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;y aquí está el Cart Controller donde intento acceder a la base de datos y actualizarla.
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) { } }Gracias