如何通过回调访问nodejs中的mongodb计数结果

How can I access mongodb count results in nodejs with a callback?

本文关键字:mongodb 结果 中的 nodejs 何通过 回调 访问      更新时间:2024-02-02

如何访问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);