Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

95
Vistas
how to update an item in a list, inside the list of items in MongoDb?

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

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda