2 回答
TA贡献1966条经验 获得超4个赞
mongoosefindOneAndUpdate 返回原始文档,如果要返回更新的文档,则需要在选项中传递 { new: true} 。
https://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate
您的查询参数也必须是这样的: {_id:req.params.patient_id}
所以你的放置路线必须是:
router.put("/:patient_id", async (req, res) => {
try {
let patient = await Patient.findById(req.params.patient_id);
if (patient) {
patient = await Patient.findOneAndUpdate(
{ _id: req.params.patient_id },
{
firstName: req.body.firstName,
lastName: req.body.lastName,
dateOfBirth: req.body.dateOfBirth,
phoneNumber: req.body.phoneNumber,
email: req.body.email,
medicalConditions: req.body.medicalConditions
},
{ new: true }
);
}
return res.json(patient);
} catch (err) {
console.error(err.message);
res.status(500).send("Server Error in update patient info");
}
});
另一种解决方案是使用findByIdAndUpdate更短的。如果没有找到文档,返回 400-Bad 请求(或 404 未找到)也是一个好习惯。(正如您在获取路线中所做的那样)
router.put("/:patient_id", async (req, res) => {
try {
let patient = await Patient.findByIdAndUpdate(
req.params.patient_id,
{
firstName: req.body.firstName,
lastName: req.body.lastName,
dateOfBirth: req.body.dateOfBirth,
phoneNumber: req.body.phoneNumber,
email: req.body.email,
medicalConditions: req.body.medicalConditions
},
{ new: true }
);
if (!patient) {
return res.status(400).json({ msg: "This patient does not exist." });
}
return res.json(patient);
} catch (err) {
console.error(err.message);
res.status(500).send("Server Error in update patient info");
}
});
添加回答
举报