skip to Main Content

All,

I can seem to figure out why the record in the database will not update. I am not 100% sure where my error is but this isn’t really providing me a great error message. Can someone please take a look at this for me?

I believe that I am calling the mongoose request properly. Thank you in advance!

$ npm mongoose -v
8.15.0

const mongoose = require("mongoose");

const CartSchema = new mongoose.Schema(
  {
    owner: {
      type: String,
      unique: true,
      required: true,
    },
    discount: {
      type: Number,
    },
    total: {
      type: Number,
    },
    items: [
      {
        itemId: {
          type: Number,
        },
        sku: {
          type: Number,
        },
        quantity: {
          type: Number,
        },
        price: {
          type: Number,
        },
      },
    ],
  },
  { timestamps: true }
);

const Cart = mongoose.model("Cart", CartSchema);

module.exports = Cart;
Record in Database
{"_id":{"$oid":"630689708997a6589635986c"},
"owner":"611afa8b9069c9126cff3357",
"total":{"$numberInt":"0"},
"items":[],
"createdAt":{"$date":{"$numberLong":"1661372784844"}},
"updatedAt":{"$date":{"$numberLong":"1661372784844"}},
"__v":{"$numberInt":"0"}}
exports.add = async (req, res, next) => {
  const { id, product } = req.body;
  const addItem = { itemId: product._id, sku: product.sku, quantity: 1, price: product.price };
  console.log(addItem);
  try {
    const updateCart = Cart.findByIdAndUpdate(id, { $addToSet: { items: addItem } }, { new: true, returnDocument: "after" });
    if (!updateCart) return next(new ErrorResponse("Unable to update the cart record", 404));
    console.log(updateCart);

    if (updateCart) {
      return sendRes(updateCart, 200, res);
    } else {
      return sendRes(updateCart, 201, res);
    }
  } catch (error) {
    console.log(error);
    next(error);
  }
};

3

Answers


  1. Chosen as BEST ANSWER

    This issue was caused by me using an ASYNC Function without the AWAIT on the DB Call.


  2. The first obvious mistake is that you’re searching for a document with the wrong field:"id", Kindly change that to "_id: id"

    Also you might need to convert the _id string you have to MongoDB Object ID, like this:

    const ObjectId = require('mongodb').ObjectId;
    
    
    Cart.updateOne({_id: new ObjectId(id)}, { $addToSet: { items: addItem } }, { new: true, returnDocument: "after" });
    

    For other update method, you need to specify the field, and also convert it to a MongoDB ID

    OR

    Cart.findByIdAndUpdate(id, { $addToSet: { items: addItem } }, { new: true, returnDocument: "after" })
    

    You do not to specify the field in findByIdAndUpdate, just pass the id to it.

    Login or Signup to reply.
  3. Please try once with this:

    Cart.findByIdAndUpdate(id, { $addToSet: { items: addItem } }, { new: true, returnDocument: "after" });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search