Karthik Karthik - 1 year ago 42
Node.js Question

Node JS mongoose Query is not producing result

Been stuck on this problem for hours. The below code:

router.route("/contact")
.get(function(req,res){
var response = {};
Contact.find({},function(err,data){
if(err) {
response = {"error" : "Error fetching data"};
} else {
response = {"message" : data};
}
res.json(response);
});
})


Above query produces result with all the contacts in the database but

router.route("/contact/department/:dept")
.get(function(req,res){
var response = {};
var arrDept = req.params.dept.split(",");
if(arrDept.length == 0){
response = {"error": " Please enter Department keywords"};
}
else{
response = {};
arrDept.forEach(function(currentValue){
Video.find({dept: '/'+currentValue+'/i'}, function(err, data){
if(err){
response[currentValue] = "No data found";
}else{
response[currentValue] = data;
}
});
});
}
res.json(response);
});


this code does not produce any output.

The code is entering the forEach loop in the else block but the query is not generating any result even if I modify the query to a basic one like

Video.find({},function(err, data){
if(err){
response[currentValue] = "No data found";
}else{
response[currentValue] = data;
}
});


The response JSON is still returned blank.

PS: Problem has been simplified as is only an example of actual problem i am facing in the code.
update after answer found.

Answer Source

Your res.json(response); in the non-working example is outside the callback of your MongoDB query, that is you are writing the response before the query's callback was actually executed and therefore your result is empty.