我正在尝试读取expressjs中的mongoDB数据并将其返回,但是收到了错误
{
"error": {
"message": "Cannot read property 'DiseaseID' of undefined"
}
}
代码是:
exports.UserDiseaseInfo = (req, res,next) => {
let retval = {};
let body = req.body;
let UId = (body.UId != undefined) ? body.UId : false;
let SubDId = (body.SubDId != undefined) ? body.SubDId: false;
if(UId==false||SubDId==false){
res.status(404).send({response:"Fail", body: req.body});
}
var subd = subDisease_model.findById(SubDId);
let data = {
response:'success',
subDisease : "XX",
diseaseId : subd[0].DiseaseID
}
res.status(200).send(data);
};
SubDiseaseModel:
const mongoose = require('mongoose');
const AddictionsSchema = new mongoose.Schema({
DiseaseID : mongoose.Schema.Types.String,
SubDisease : mongoose.Schema.Types.String
});
module.exports = mongoose.model('SubDiseaseMaster', AddictionsSchema, 'SubDiseaseMaster');
数据库数据:
db.SubDiseaseMaster.find({})
{ "_id" : ObjectId("5ad0850efdcab0ab875c4890"), "DiseaseID" : "5ad06decfdcab0ab875c4838", "SubDisease" : "Acidity" }
JSON致电:
POST /api/UserDiseaseInfo HTTP/1.1
Host: 1nature.in
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: 62e22748-5c30-3f4b-4852-fc0bab68db0d
{
"UId":"A",
"SubDId": "5ad0850efdcab0ab875c48a4"
}
知道我哪里失败了?
答案 0 :(得分:0)
findById
返回单个文档,您将其视为数组并尝试阅读如下:
let data = {
response:'success',
subDisease : "XX",
diseaseId : subd[0].DiseaseID // <- here is the problem
}
将subd[0].DiseaseID
替换为subd.DiseaseID
,问题将得到解决。