MongoDB count collection Node.js

2019-01-26 06:24发布

问题:

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!

回答1:

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);
    });
  });
};