PUT请求无法使用MongoDB,Node和Express更新条目的问题



使用MERN堆栈,并且无法获取PUT请求以在这种情况下更新患者信息。

患者路线 - 患者.js

//@route   POST api/patients
//@desc    Create patient profile
//@access  Private, patient information
router.post('/', [ auth,
check('firstName', 'First Name is required')
.not()
.isEmpty(),
check('lastName', 'Last name is required')
.not()
.isEmpty(),
check('medicalConditions', 'Medical Conditions are required')
.not()
.isEmpty()
], 
async (req, res) => {
const errors = validationResult(req);
if(!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const {
firstName,
lastName,
dateOfBirth,
phoneNumber,
email,
medicalConditions
} = req.body
//Build patient object
const patientFields = {}
if(firstName) patientFields.firstName = firstName;
if(lastName) patientFields.lastName = lastName;
if(dateOfBirth) patientFields.dateOfBirth = dateOfBirth;
if(phoneNumber) patientFields.phoneNumber = phoneNumber;
if(email) patientFields.email = email;
if(medicalConditions) {
patientFields.medicalConditions = medicalConditions.split(',').map(medicalCondition => medicalCondition.trim());
}
try {
patient = new Patient(patientFields);
await patient.save();
res.json(patient)
} 
catch (err) {
console.error(err.message);
res.status(500).send('Server Error in Create/Update Patient');
}
}
);
//@route   GET api/patients/:patient_id
//@desc    Get patient by ID
//@access  Private, patient information
router.get('/:patient_id', auth, async (req, res) => {
try {
const patient = await Patient.findById(req.params.patient_id);
if(!patient) {
return res.status(400).json({ msg: "This patient does not exist." });
}
res.json(patient)
} 
catch (err) {
console.error(err.message);
if(err.kind == 'ObjectId') {
return res.status(400).json({ msg: 'Patient not found' })
}
res.json(500).send({ msg: 'Server Error in get patient by user ID' })
}
});
//@route   PUT api/patients/:patient_id
//@desc    Update patient information
//@access  Private, patient information
router.put('/:patient_id', async (req,res) => {
try {
let patient = await Patient.findById(req.params.patient_id); 
if(patient) {
patient = await Patient.findOneAndUpdate(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 
}
);
}
return res.json(patient);
} 
catch (err) {
console.error(err.message);
res.status(500).send('Server Error in update patient info')
}
});

我一直在引用此项目的教程,但在教程中,创建配置文件路由还更新了配置文件,因为它引用了登录用户的 ID。

当我用邮递员测试这一点时,我正在发送我要更新的患者 url 中的patient_id,它会发回数据库中不同患者的信息。

如何修改放置请求以更新患者信息?

谢谢!

猫鼬findOneAndUpdate返回原始文档,如果要返回更新的文档,则需要在选项中传递{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");
}
});

您要么永远找不到患者,要么更新时出错。尝试在你的更新函数上做一个.then和.catch,看看抛出的任何错误。

最新更新