繁体   English   中英

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

[英]Trouble with a PUT request not updating the entry using MongoDB, Node and Express

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

患者路线- Patient.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。

当我使用 Postman 进行测试时,我将在我想更新的患者的 url 中发送患者 ID,并将其发送回数据库中不同患者的信息。

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

谢谢!

mongoose findOneAndUpdate返回原始文档,如果要返回更新后的文档需要在 options 中传入 {new:true}。

https://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate

您的查询参数也必须是这样的: {_id:req.params.patient_id}

所以你的 put 路线必须是:

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 未找到)。 (就像你在 get 路线中所做的那样)

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

您要么永远找不到患者,要么更新时出错。 尝试在更新 function 上执行 a.then &.catch 并查看抛出的任何错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM