我如何使用callback访问nodejs中的mongodb计数结果?

如何访问nodej中的mongodb计数结果,以便asynchronous请求可以访问结果? 我可以得到结果并更新数据库,但是asynchronous请求无法访问variables,或者variables是空的,当下一个asynchronous请求发生时,variables似乎会更新。 该请求不得等待查询完成,并且下一个请求将填充上一个请求的variables。

testOne.increment = function(request) { var MongoClient = require('mongodb').MongoClient, format = require('util').format; MongoClient.connect('mongodb://127.0.0.1:27017/bbb_tracking', function(err, db) { if (err) throw err; collection = db.collection('bbb_tio'); collection.count({vio_domain:dom}, function(err, docs) { if (err) throw err; if (docs > 0) { var vio_val = 3; } else { var vio_val = 0; } if (vio_val === 3) { event = "New_Event"; var inf = 3; } db.close(); console.log("docs " + docs); }); }); }; 

在上面,即使variables被设置在范围内,它们也不是asynchronous定义的。 我可以得到一些正确的结构指导,所以variables在callback中填充。 谢谢!

由于count函数是asynchronous的,因此您需要将callback函数传递给increment函数,以便在从数据库返回count时,代码可以调用callback函数。

 testOne.increment = function(request, callback) { var MongoClient = require('mongodb').MongoClient, format = require('util').format; MongoClient.connect('mongodb://127.0.0.1:27017/bbb_tracking', function(err, db) { if (err) throw err; var collection = db.collection('bbb_tio'); // not sure where the dom value comes from ? collection.count({vio_domain:dom}, function(err, count) { var vio_val = 0; if (err) throw err; if (count > 0) { vio_val = 3; event = "New_Event"; var inf = 3; } db.close(); console.log("docs count: " + count); // call the callback here (err as the first parameter, and the value as the second) callback(null, count); }); }); }; testOne.increment({}, function(err, count) { // the count would be here... }); 

(我不明白你所使用的variables是什么意思,或者为什么以后不使用它们,所以我只是做了一些清理工作,variables被限制在函数块中,然后挂起来,所以你不用如果你用vio_val完成的话,就不需要重新声明它们)。

你可以使用“asynchronous”模块。 它使代码更清晰,更易于debugging。 在下面的文章中看看GitHub中的代码adduser.js&deleteuser.js

http://gigadom.wordpress.com/2014/11/05/bend-it-like-bluemix-mongodb-using-auto-scaling-part-2/

问候Ganesh