Node.js mongoose.findOne返回null
我在express中创建了路由,将患者数据输入mongodb,并从数据库中获取数据。预期的结果是获得患者档案作为回报。get路径中存在一些错误,因此我无法看到患者的个人信息。请帮忙做同样的事情Node.js mongoose.findOne返回null,node.js,mongodb,express,mongoose,mongoose-populate,Node.js,Mongodb,Express,Mongoose,Mongoose Populate,我在express中创建了路由,将患者数据输入mongodb,并从数据库中获取数据。预期的结果是获得患者档案作为回报。get路径中存在一些错误,因此我无法看到患者的个人信息。请帮忙做同样的事情 // @ route GET api/patient/:patientId // @ desc Get patient by patientId // @ access Private router.get('/:patientId', auth, async (req, res) => {
// @ 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;
您是基于
patient
而不是patientId
进行查询的,该字段是您指定为自动递增的字段
将您的查询修改为:
const patient_profile = await Patient.findOne({
patientId: req.params.patientId
}).populate('patient',['name','phonenumber']);
我希望这能解决您的问题。您为什么要使用patientId而不仅仅是id?req.params.patientId是否符合您的期望?它是否存在于数据库中?它们是相同的类型吗?嗨,多米尼克,是的,数据库中有。我已经用“猫鼬自动增量”创建了相同的。我之所以添加此项,是因为应用程序中需要通过ID搜索患者。console.log(patient_profile)返回空值。请帮助@Dominic我试图通过mongoDb Id(即_Id)更改代码以获取患者。findone函数返回第一个文档。请帮助我。我卡住了!嗨,史蒂夫。。非常感谢你的帮助。。这管用!我是javascript新手,你能帮我查询按电话号码查找患者吗?你只需要将
phonenumber
作为查询对象的属性传递:patient.findOne({phonenumber:'0123456789'})
phonenumber:req.params.phonenumber,我正在尝试此查询。控制台返回“null”。你好,史蒂夫!谢谢你的支持。我发现了我的错误。我的电话号码也是这样。我尝试了新路线,它成功了!
const patient_profile = await Patient.findOne({
patientId: req.params.patientId
}).populate('patient',['name','phonenumber']);