我能够通过我的nodejs api连接到mongodb,但由于某些原因数据未返回。当我查询从控制台MongoDB的,这里是我得到:Mongodb数据不会返回到nodejs api
MongoDB Enterprise > db.patients.find();
{ "_id" : ObjectId("58c9a5dd1eb8c7c1c68778ca"), "FName" : "n", "LName" : "ri", "Email" : "[email protected]", "phone" : "1234567890" }
这里是从的NodeJS代码:
app.get('/api/patients',function(req,res){
Patient.getPatients(function(err,patients){
if(err){
throw err;
}
console.log(patients.length);
res.json(patients);
});
});
,这是getPatients方法:
var Patient = module.exports = mongoose.model('patient',patientSchema);
// get patients
module.exports.getPatients = function(callback,limit){
Patient.find(callback);
}
但浏览器总是显示“[]”并且没有数据。当我在API中查看数组的长度(console.log(patients.length))时,我得到0.不知道为什么数据没有返回。 有人可以指出我可能是什么问题?
更新基于建议
,我没有以下更改。我创建了2个集合以确保集合存在。所以我有病人和病人收藏。
MongoDB Enterprise > db.patient.find();
{ "_id" : ObjectId("58cfe4551eb8c7c1c68778cc"), "FName" : "V", "LName" : "K", "Email" : "[email protected]", "phone" : "1234567890" }
{ "_id" : ObjectId("58cfe4601eb8c7c1c68778cd"), "FName" : "V1", "LName" : "K1", "Email" : "[email protected]", "phone" : "1234567890" }
MongoDB Enterprise > db.patients.find();
{ "_id" : ObjectId("58cfe42d1eb8c7c1c68778cb"), "FName" : "V", "LName" : "K", "Email" : "[email protected]", "phone" : "1234567890" }
下面是从文件的NodeJS代码:
var mongoose = require('mongoose');
var patientSchema = mongoose.Schema({
FName: {
type : String
},
LName: {
type : String
},
Email: {
type : String
},
phone: {
type : String
},
},
{collection : 'patient'});
var Patient = module.exports = mongoose.model('patient',patientSchema);
// get patients
module.exports.getPatients = function(callback,limit){
console.log('test2');
Patient.find({}, function(err, patients) {
if (err) throw err;
// object of all the users
console.log(patients.length);
});
}
当我运行这段代码,它打印“测试2”和“0”但对我来说没有实际效果。有人可以帮忙吗?
架构在我的更新中定义和共享。请检查.. – DevHelp
你可以推你的代码到github,我可以克隆它并解决问题..? –
https://github.com/justdev123/Mean - >它可能是一个大项目,但相关的文件是1)src \ models \ patient.js 2)app.js – DevHelp