Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

94
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda