0

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.

  • You mean when you console.log the response right? But what to you see as the actual response or if your use JSON.stringify on the parsed object instead? – Neil Lunn Apr 13 '14 at 03:52

2 Answers2

1

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);
});
Community
  • 1
  • 1
PeterVC
  • 4,574
  • 2
  • 16
  • 14
0

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

A. Jesse Jiryu Davis
  • 23,641
  • 4
  • 57
  • 70