Reputation: 1
I have a node.js server that calls a function that needs to query a Mongodb database.
exports.zonetotal = function(db) {
return function(req, res) {
var inZone1 = 2;
inZone1 = db.collection('driveby').count();
var items = [
{"zone":"1" , "number":inZone1}
];
{
res.json(items);
}
}
};
When I try to use this function and display the results in a table on a webpage i just get a result that says object object. If I just say var inZone1 = 2; then the number displays so I do not think that it is an issue with the way I am trying to send the data, I think that it is an issue with the query. Any ideas, thanks.
Upvotes: 0
Views: 1255
Reputation: 4604
collection.count() is asynchronous. You need to provide a callback that performs the render. See this. Just move your rending code inside the callback like so:
db.collection('driveby').count({zone:1}, function(err, count) {
console.log(count + "records in db");
console.log("There are " + count + " records in db");
var items = [ {"zone":"1" , "number":count} ];
res.json(items);
});
Upvotes: 1
Reputation: 24007
The Node MongoDB driver is async, so you'll need to pass a callback to "count" and execute res.json from within the callback:
http://mongodb.github.io/node-mongodb-native/api-generated/collection.html#count
Upvotes: 0