【问题标题】:mongoose.findOne return nullmongoose.findOne 返回 null
【发布时间】:2019-11-03 09:32:19
【问题描述】:

我已经在 express 中创建了将患者数据输入到 mongodb 并从数据库中获取数据的路由。预期的结果是获得患者资料作为回报。获取路线中存在一些错误,因此我无法看到 patient_profile 的响应。请提供相同的帮助。

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

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

        patient: req.params.patientId

      }).populate('patient',['name','phonenumber']);
      //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;
const mongoose= require('mongoose');
autoIncrement = require('mongoose-auto-increment');
const config =require('config');
const db=config.get('mongoURI');

var connection = mongoose.createConnection(db);

autoIncrement.initialize(connection);

const PatientSchema = new mongoose.Schema({
    name:{
        type:String,
        required: true
    },
    phonenumber:{
        type:Number,
        required:true
    },
    date: {
        type: Date,
        default: Date.now
    },
    slider_1:{
        type:Number,
        required: true
    },
    slider_2:{
        type:Number,
        required:true
    },
    slider_3:{
        type:Number,
        required:true
    }

});
PatientSchema.plugin(autoIncrement.plugin, {
  model:'Patient',
   field:'patientId',
   startAt:1,
   incrementBy:1
});

module.exports=Patient=mongoose.model('patient',PatientSchema,'patient');

【问题讨论】:

  • 你为什么使用 patientId 而不仅仅是 _id? req.params.patientId 是您所期望的吗?它是否存在于数据库中?它们是同一类型吗?
  • 嗨 Dominic 是的,患者 ID 存在于数据库中。我使用“mongoose-auto-increment”创建了相同的内容。由于应用程序中需要通过 ID 搜索患者的功能,我添加了此功能。 console.log(patient_profile) 返回 null。请帮忙!
  • @Dominic 我尝试更改代码以通过 mongoDb Id 获得耐心,即 _id。findone 函数返回第一个文档,你能帮帮我吗?我卡住了!

标签: node.js mongodb express mongoose mongoose-populate


【解决方案1】:

您是基于patient 而不是patientId 进行查询,这是您指定自动递增的字段。

将您的查询修改为:

const patient_profile = await Patient.findOne({

  patientId: req.params.patientId

}).populate('patient',['name','phonenumber']);

我希望这能解决你的问题。

【讨论】:

  • 嗨史蒂夫..非常感谢您的帮助..这行得通!我是 javascript 新手,你能帮我查询一下通过电话号码找到病人吗
  • 您只需将phonenumber 作为查询对象的属性传递:Patient.findOne({ phonenumber: '0123456789' })
  • phonenumber: req.params.phonenumber ,我正在尝试这个查询。控制台返回“null”。请帮忙
  • 嗨史蒂夫!感谢您的支持..找出我的错误。我使用相同的电话号码路由。我尝试了新的路线,它奏效了!
猜你喜欢
  • 2020-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-21
相关资源
最近更新 更多