如何在nodejs中访问mongodb计数结果,以便异步请求可以访问结果?我可以获得结果并更新数据库,但异步请求无法访问变量或变量为空,并且在下一个异步请求发生时,变量似乎会更新。请求不能等待查询完成,下一个请求将填充先前请求的变量。
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);
});
});
};
在上文中,即使将vars设置在范围内,也不会异步定义。我是否可以获得有关正确构造此类的一些指导,以便在回调中填充变量。谢谢!
答案 0 :(得分:2)
由于count
函数是异步的,因此您需要将回调传递给increment
函数,以便在从数据库返回count
时,代码可以调用回调。
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...
});
(我不明白你使用的变量是什么意思,或者为什么以后不再使用它们,所以我只是做了一些清理工作。变量的范围是功能块并提升到该函数,因此您不需要像使用vio_val
)那样在每个if块中重新声明它们。
答案 1 :(得分:0)
你可以使用' async'模块。它使代码更清晰,更容易调试。请查看GitHub中adduser.js&的代码。以下帖子中的deleteuser.js
http://gigadom.wordpress.com/2014/11/05/bend-it-like-bluemix-mongodb-using-auto-scaling-part-2/
此致 内甚
答案 2 :(得分:0)
length给您结果数组的数量
const userdata = await User.find({ role: role, 'name': new RegExp(searchkey, 'i') },{date: 0,__v:0,password:0}).
sort(orderObj)
.limit(limit)
.skip(skip);
console.log(userdata.length);