MongoDB计数集合Node.js [英] MongoDB count collection Node.js

查看:64
本文介绍了MongoDB计数集合Node.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过Node.js与MongoDB进行交互,并且在count()方法上遇到了一些麻烦.我正在使用 node-mongodb-native ,看来我正在做的事情应该可以工作.我的代码示例:

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

我确定一切都存在(也定义了coll和cursor),但是仅当我的query.params字段为空(即查找整个集合的计数)时,它才有效.因此,如果我尝试使用任何类型的选择器运行查找,查找将起作用,但是它拒绝依靠返回的游标.从我在网上阅读的内容来看,这似乎是正确的方法,但是显然有些错误.感谢您提供的所有帮助!

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!

推荐答案

如果不需要游标,则应这样编写代码:

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

这篇关于MongoDB计数集合Node.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆