Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

93
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!