在一个variables中获取计数的mongodb集合的值
我正在尝试从MongoDB中的集合中检索logging的值
这是我的来源。
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(); };
问题是,callback输出寄存器的数量,但callback输出0,我不知道如何将该值保存在一个variables。
因为db.collection
和collection.count
是asynchronous方法,所以执行第二个console.log
语句之后 , c
variables会被设置。
所以你想用c
做的任何事情都必须在collection.count
callback中发生。
你的代码不尊重node.js IO的asynchronous性质。
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(); }); }); };