MongoDB 计数集合 Node.js

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9318086/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:12:06  来源:igfitidea点击:

MongoDB count collection Node.js

node.jsmongodb

提问by MrJaeger

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

我正在尝试通过 Node.js 与 MongoDB 交互,但在使用 count() 方法时遇到了一些问题。我正在使用node-mongodb-native,看起来我正在做的事情应该可以工作。我的代码示例:

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!

我确信一切都存在(又名 coll 和 cursor 都已定义),但它仅在我的 query.params 字段为空时才有效(即查找整个集合的计数)。因此,如果我尝试使用任何类型的选择器运行查找,则查找有效,但它拒绝依赖返回的游标。从我在网上阅读的内容来看,这看起来是正确的方法,但显然有些问题。感谢您的任何帮助!

回答by Aleksandar Vucetic

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