Maaart
Maaart

Reputation: 55

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 :)

Upvotes: 2

Views: 308

Answers (1)

Gibbs
Gibbs

Reputation: 22964

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

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

Upvotes: 1

Related Questions