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

111
Views
Updating field in Array with MongoDB and NodeJS

I'm new to backend and trying to make a shopping cart with NodeJs and MongoDb. I tried many thing but i can't update the quantity field of a product.

This is the schema

const mongoose = require('mongoose');

const itemsSchema = mongoose.Schema(
  {
    prodId: String,
    name: String,
    price: Number,
    qty: {
      type: Number,
      default: 1,
      min: 1,
    },
  },
  {
    timestamps: true,
  }
);

const cartSchema = mongoose.Schema(
  {
    total: {
      type: Number,
    },
    products: [itemsSchema],
  },
  {
    timestamps: true,
  }
);

const Cart = mongoose.model('carts', cartSchema);

module.exports = Cart;

This is the controller

const Cart = require('../models/cart');

exports.postItemToCart = async (req, res) => {
  const { prodId } = req.body;

  Cart.updateOne(
    { 'products.prodId': prodId },
    { $inc: { 'products.qty': 1 } }
  );

  return res.status(200).send(Cart);
};

This is the cart

[
  {
    _id: '60062c7a9b0bfd350b3eb755',
    __v: 3,
    createdAt: '2021-01-19T00:48:58.006Z',
    products: [
      {
        qty: 1,
        _id: '6006333bd00fe96af648d308',
        prodId: '1111',
        name: 'Product One',
        price: 24.22,
        updatedAt: '2021-01-19T01:17:47.034Z',
        createdAt: '2021-01-19T01:17:47.034Z',
      },
      {
        qty: 1,
        _id: '600634337f3eba6b451a26e5',
        prodId: '2222',
        name: 'Product Two',
        price: 24.22,
        createdAt: '2021-01-19T01:21:55.417Z',
        updatedAt: '2021-01-19T01:21:55.417Z',
      },
    ],
    total: 48.44,
    updatedAt: '2021-01-21T02:19:49.955Z',
  },
];

I can change and update in the Mongoose documentation console, but i can't apply the same code on my project.

Please help :)

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

positional operator will help you to update the first matching array element.

Cart.updateOne(
    { 'products.prodId': prodId },
    { $inc: { 'products.$.qty': 1 } } //note dollar sign
  );

over 4 years ago · Santiago Trujillo Report
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!