2

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

0

1 Answer 1

1

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

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

Sign up to request clarification or add additional context in comments.

2 Comments

Hi Gibbs! I tried but it doesn't work. I have this error" (node:6842) UnhandledPromiseRejectionWarning: TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received function model [0] at Function.from (buffer.js:331:9)
Finally i could solved my problem. I was using the last version of Mongoose, I downgraded to "mongoose": "5.2.8" and now all my problems are gone! Thank you @gibbs!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.