【问题标题】:Mongoose.findOne returns same documentMongoose.findOne 返回相同的文档
【发布时间】:2019-06-21 01:29:52
【问题描述】:

我正在尝试使用 express 作为后端通过其 id 获取 mongodb 文档。每次我请求路由时,findOne & populate 查询都会返回相同的文档。我想按 Id 返回患者数据。有人可以帮我解决这个问题吗?我是 JavaScript 新手。

// @ route  GET api/profile/patient/:patientId
// @ desc   Get patient by patientId
// @ access Private

router.get('/:patient_id', auth, async (req, res) => {
    try {
      const patient_profile = await Patient.findOne({

        patient: req.params._id

      }).populate('patient');
      //console.log(patient);
      console.log(patient_profile);
      if (!patient_profile) return res.status(400).json({ msg: 'Patient not found' });

      res.json(patient_profile);    
    } catch (err) {
      console.error(err.message);
      if (err.kind == 'ObjectId') {
        return res.status(400).json({ msg: 'Profile not found' });
      }
      res.status(500).send('Server Error');
    }
  });

module.exports=router;

【问题讨论】:

  • req.params.patient_id?
  • 嗨 Ayush.. 该函数现在返回 null.. 请帮助

标签: node.js mongodb express mongoose


【解决方案1】:

要访问请求参数上的 ID,请使用下面的代码...

req.params.patient_id

你的错误是

req.params._id

【讨论】:

  • 嗨詹姆斯..仍然函数返回相同的文档。
  • 尝试使用 findById(req.params.patient_id, function(err, data){// do stuff here}) 而不是 'findOne'。祝你好运!
  • 对于模型“患者”的路径“_id”处的值“{患者:'5d0ba1b6f011b1538c0fb0bc'}”转换为 ObjectId 失败 嗨,詹姆斯在控制台上获得此输出
  • remove '.populate('patient')'... populate 函数仅用于获取引用的文档。
  • 嗨詹姆斯..你也可以帮助我查询以通过电话号码查找记录..我的数据库中有电话号码字段。在我刚接触编程时请求您的帮助。
猜你喜欢
  • 2020-08-25
  • 2019-11-03
  • 2019-05-04
  • 2012-08-19
  • 2019-10-04
  • 2023-03-20
  • 1970-01-01
  • 2018-05-23
  • 1970-01-01
相关资源
最近更新 更多