2

我正在尝试从 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,我不知道如何将该值保存在变量中。

4

2 回答 2

1

因为db.collectionandcollection.count是异步方法,所以在执行第二条语句c设置变量。console.log

所以你想做的任何事情都c必须在collection.count回调中发生。

于 2013-08-26T13:55:42.707 回答
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();
                    });
        });
};
于 2013-08-26T14:05:28.480 回答