【问题标题】:while updating document with mongoose, adds _id使用 mongoose 更新文档时,添加 _id
【发布时间】:2022-02-09 22:19:20
【问题描述】:

我正在尝试使用猫鼬模型方法进行练习。我试图用findByIdAndUpdate 方法更新我的文档的某些部分,它确实有效,但创建了一些我不想看到的额外_id

来自 server.js:

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

这里来自 updateRoute

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

来自控制器

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

这是架构和模型

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

这是我的 URL 和 JSON 正文

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

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

这是结果

{
    "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"
    }
}

我不想在对象数组中获取_id 键。我希望他们像

...
"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
            }
        ]
...

【问题讨论】:

    标签: javascript node.js api mongoose methods


    【解决方案1】:

    如果您想从查询响应中删除它们,请在查询中使用 .select,如下所示:

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

    这将使结果排除数组元素中的所有 _id 属性。 如果您想从元素中完全删除 _id,您可以像这样定义您的架构:

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

    【讨论】:

      猜你喜欢
      • 2015-02-09
      • 1970-01-01
      • 2016-01-22
      • 2016-06-04
      • 1970-01-01
      • 1970-01-01
      • 2021-10-11
      • 2018-04-18
      • 2012-10-27
      相关资源
      最近更新 更多