Home > Net >  while updating document with mongoose, adds _id
while updating document with mongoose, adds _id

Time:02-10

I was trying to make practise with mongoose model-methods. I was trying to update some part of my document with the method findByIdAndUpdate and it works actually, but creates some extra _id which I dont want to see it.

here it from server.js:

 app.use("/update", updateRoute);

here ist from the updateRoute

router.patch("/grades/:id", searchGradeAndUpdate);

from controller

exports.searchGradeAndUpdate = async (req, res) => {
  try {
    const result = await Restaurant.findByIdAndUpdate(req.params.id, { grades: req.body.grades }, { new: true }).lean()
    res.status(200).json({ msg: "restaurant found! SUCCESS!!!", result })
  } catch (error) {
    res.status(404).json({ msg: "restaurant NOT found!! FAIL!!!" })
  }
};

here is the schema and model

    const { Schema, model } = require("mongoose");

const restaurantSchema = new Schema({
  address: {
    building: String,
    coord: [Number],
    street: String,
    zipcode: String
  },
  borough: String,
  cuisine: String,
  grades: [
    {
      date: { type: String, default: new Date() },
      grade: String,
      score: Number
    }
  ],
  name: String,
  restaurant_id: String
})

exports.Restaurant = model("restaurant", restaurantSchema);

that's my URL and JSON as a body

http://localhost:3001/update/grades/5eb3d668b31de5d588f4292a

{"grades": [
            {
                
                "grade": "f",
                "score": 52
            },
            {
                
                "grade": "A",
                "score": 100
            }
        ]
}

here is the result

{
    "msg": "restaurant found! SUCCESS!!!",
    "result": {
        "_id": "5eb3d668b31de5d588f4292a",
        "address": "berlin",
        "borough": "spandau",
        "cuisine": "Anatolian",
        "grades": [
            {
                "date": "Wed Feb 09 2022 14:29:44 GMT 0100 (Central European Standard Time)",
                "_id": "6203c2e9fbf39efe8e5cf00b",
                "grade": "f",
                "score": 52
            },
            {
                "date": "Wed Feb 09 2022 14:29:44 GMT 0100 (Central European Standard Time)",
                "_id": "6203c2e9fbf39efe8e5cf00c",
                "grade": "A",
                "score": 100
            }
        ],
        "name": "Ramazan's Kitchen ",
        "restaurant_id": "40356018"
    }
}

I dont want the get the _id key inside of the array of objects. I wanted them to be like

...
"grades": [
            {
                "date": "Wed Feb 09 2022 14:29:44 GMT 0100 (Central European Standard Time)",
                "grade": "f",
                "score": 52
            },
            {
                "date": "Wed Feb 09 2022 14:29:44 GMT 0100 (Central European Standard Time)",
                "grade": "A",
                "score": 100
            }
        ]
...

CodePudding user response:

if you want to delete them from your query response only use .select in your query like so:

    const result = await Restaurant.findByIdAndUpdate(req.params.id, {grades:req.body.grades }, { new: true }).select('-grades._id').lean()

this will make the result exclude all _id properties from the elements of your array. if you want to delete _id from your elements completely you can define your schema like so:

  subschema =  mongoose.Schema({
      date: { type: String, default: new Date() },
      grade: String,
      score: Number
  }, { _id : false });
  const restaurantSchema = new Schema({
    address: {
      building: String,
      coord: [Number],
      street: String,
      zipcode: String
    },
    borough: String,
    cuisine: String,
    grades: [subschema],
    name: String,
    restaurant_id: String
  })
  • Related