【发布时间】: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