Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB count collection Node.js

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!

like image 391
MrJaeger Avatar asked Feb 16 '12 19:02

MrJaeger


1 Answers

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);
    });
  });
};
like image 104
Aleksandar Vucetic Avatar answered Oct 06 '22 10:10

Aleksandar Vucetic