Reputation: 1121
I am trying to get all consultation of a patient and if a patient has more than one consultation then i need to iterate through foreach/map, here is my implement of this but this is not working, please help
in below code when i am hitting the api then the response i am receiving is this: No default engine was specified and no extension was provided if i am running this code without foreach then it is working and i am getting doc length
router.post('/get/consultations', function(req, res){
console.log("consultation"+req.body.patient_id);
var dc = {};
consultation.find({"patient":req.body.patient_id}).forEach(function(doc){
console.log(doc.length);
//dc.push(doc);
});
res.json(dc);
});
Upvotes: 0
Views: 393
Reputation: 99
According to Mongoose Doc http://mongoosejs.com/docs/queries.html
When a callback function:
- is passed, the operation will be executed immediately with the results passed to the callback.
- is not passed, an instance of Query is returned, which provides a special query builder interface.
since your statement
consultation.find({"patient":req.body.patient_id})
didn't pass callback function as an argument. This statement returns a Query object which you can execute by using .exec eg.
// .find returns a Query object
var query = Person.find({ 'name.last': 'Ghost' });
// execute the query at a later time
query.exec(function (err, person) {
if (err) return handleError(err);
console.log('%s %s is a %s.', person.name.first, person.name.last, person.occupation) // Space Ghost is a talk show host.
})
so your code should be either one of these way
// using exec
consultation.find({"patient":req.body.patient_id}).exec(function(docs){
docs.forEach(function(doc){
console.log(doc.length);
});
// using callback
consultation.find({"patient":req.body.patient_id}, function(err,docs){
docs.forEach(function(doc){
console.log(doc.length);
});
});
// using promise (mongoose 4+)
consultation.find({"patient":req.body.patient_id}).then( function(docs){
docs.forEach(function(doc){
console.log(doc.length);
});
});
Upvotes: 3