【发布时间】: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