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

110
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
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