Home > Blockchain >  Mongoose - findByIdAndUpdate
Mongoose - findByIdAndUpdate

Time:08-25

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);
  }
};

CodePudding user response:

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.findByIdAndUpdate({_id: new ObjectId(id)}, { $addToSet: { items: addItem } }, { new: true, returnDocument: "after" });

CodePudding user response:

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

CodePudding user response:

Please try once with this:

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