12

I am attempting to interface with MongoDB through Node.js and am having some trouble with the count() method. I am using node-mongodb-native and it looks like what I am doing should work. My code sample:

var get_total_num_docs = function(db_client, query, cb){
  db_client.collection(query['collection'], function(e, coll) {
    coll.find(query.params, query.options, function (e, cursor) {
      cursor.count(function (e, count) {
        console.log(count);
        return cb(e, count);
      });
    });
  });
};

I am sure that everything exists (aka coll and cursor are both defined), but it only works if my query.params field is empty (i.e. finding the count of an entire collection). So if I am trying to run a find with any kind of selector, the find works, but then it refuses to count on the returned cursor. From what I've read online this looks like the correct way to do it, but obviously something is wrong. Thanks for any and all help!

6
  • What do you mean when you say it refuses to count? Is it giving you the wrong count or throwing an error? Commented Feb 16, 2012 at 20:24
  • As in it literally just never finishes, aka the callback passed to count is never called. I've run it for around 10 minutes and it just never finishes. The coll.find call takes a very short amount of time, but something just isn't working with the count. Commented Feb 16, 2012 at 20:26
  • Have you tried console.logging each error object you receive? And what are the query parameters and options being used? Commented Feb 16, 2012 at 22:05
  • without the actual parameters passed in it's hard to understand what's going on. you should also print out any errors that you are getting. Sometimes these issue are related to people closing the db before the query finished Commented Feb 20, 2012 at 11:51
  • Take a look at this post - very similar method to get the count. stackoverflow.com/questions/25473650/… Commented Aug 19, 2015 at 15:40

1 Answer 1

26

If you don't need a cursor, you should write your code like this:

var get_total_num_docs = function(db_client, query, cb){
  db_client.collection(query['collection'], function(e, coll) {
    coll.find(query.params, query.options).count(function (e, count) {
      console.log(count);
      return cb(e, count);
    });
  });
};
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.