如何通过回调访问nodejs中的mongodb计数结果
How can I access mongodb count results in nodejs with a callback?
如何访问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);
});
});
};
在上文中,即使在范围中设置了变量,它们也不是异步定义的。我能得到一些关于正确构建这个的指导吗?这样就可以在回调中填充变量了。非常感谢。
由于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块中重新声明它们)
您可以使用"async"模块。它使代码更加干净,更易于调试。看看GitHub中adduser.js&deleteuser.js
http://gigadom.wordpress.com/2014/11/05/bend-it-like-bluemix-mongodb-using-auto-scaling-part-2/
问候Ganesh
长度可以计算结果数组
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);
相关文章:
- Mongodb$in以与数组中相同的顺序获取结果
- 无法使用streams/highland.js从mongodb的结果中获取数据
- 需要呈现MongoDB查询返回结果的特定索引/位置
- MongoDB:$addToSet Meteor中的重复结果回调
- MongoDB MonkAPI根据数据库请求之外可用的查找结果设置变量
- mongodb-mongoose-find-如何获得适用的字符串作为结果
- 如何通过回调访问nodejs中的mongodb计数结果
- 如何在 mongodb 中获取更新查询写入结果
- 在 meteor 中使用 MongoDB 聚合时无法获得正确的结果
- MongoDB查询结果作为循环控制器
- MongoDB mapReduce方法意外结果
- 如何在MongoDB-Shell中正确迭代搜索结果
- 在谷歌图表中显示MongoDB结果
- 如何:将node.js mongodb结果传递给angularjs
- Mongoose/MongoDB 结果字段在 Javascript 中显示为未定义
- 操作MongoDB结果以动态生成字段名
- 用Node发送MongoDB结果
- 检索回调函数范围外的MongoDB结果
- 使用本地Node.js驱动程序将MongoDB结果写入文件
- 向MongoDB结果添加额外的字段可以有效地进行