在变量中检索count mongodb集合的值

时间:2013-08-26 13:41:36

标签: node.js mongodb count

我正在尝试从Mongo DB中的集合中检索记录的值

这是我的来源。

exports.procc = function(req, res) {

        db.collection('search', function(err, collection) {
                    collection.count({'str':'car'},function(err, count) {
                       console.log(count+' records');//Prints 2 records
                       c=count;     
                    });
        });
        console.log('records= '+c);//print 0 records
 res.end();
};

问题是,在回调中打印了寄存器的编号,但是回调中输出0并且我不知道如何在变量中保存该值。

2 个答案:

答案 0 :(得分:1)

因为db.collectioncollection.count是异步方法,所以{/ 1}}变量在执行第二个c语句后得到

因此,您要对console.log进行的操作必须在c回调中进行。

答案 1 :(得分:0)

您的代码不尊重node.js IO的异步性质。

exports.procc = function(req, res) {
        db.collection('search', function(err, collection) {
                    collection.count({'str':'car'},function(err, count) {
                       console.log('records= ' + count);//print 0 records
                       res.end();
                    });
        });
};