最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I access mongodb count results in nodejs with a callback? - Stack Overflow

programmeradmin3浏览0评论

How do you access mongodb count results in nodejs so the result can be accessible to the asynchronous request? I can get the result and update the database but the asynchronous request fails to access the vars or the vars are empty and the vars appear to be updated when the next asynchronous request is made. The request must not be waiting for the query to finish and the next request is filled with the previous request's 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);
        });       
   });                    
};

In the above, even when the vars are set in scope they are not defined asynchronously. Can I get some guidance on structuring this properly so the vars are populated in the callback. Thank you!

How do you access mongodb count results in nodejs so the result can be accessible to the asynchronous request? I can get the result and update the database but the asynchronous request fails to access the vars or the vars are empty and the vars appear to be updated when the next asynchronous request is made. The request must not be waiting for the query to finish and the next request is filled with the previous request's 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);
        });       
   });                    
};

In the above, even when the vars are set in scope they are not defined asynchronously. Can I get some guidance on structuring this properly so the vars are populated in the callback. Thank you!

Share Improve this question edited Dec 1, 2013 at 21:19 WiredPrairie 59.8k18 gold badges117 silver badges145 bronze badges asked Dec 1, 2013 at 20:50 user2948977user2948977 451 gold badge2 silver badges7 bronze badges 2
  • 1 Can you clarify your question? It's not clear what the problem is. – JohnnyHK Commented Dec 1, 2013 at 21:06
  • 1 I changed the question to "How can I access mongodb count results in nodejs with a callback?" I cannot get the var results into a callback that waits for the query to finish. Does that help? Thank You! – user2948977 Commented Dec 1, 2013 at 21:16
Add a ment  | 

3 Answers 3

Reset to default 2

Since the count function is asynchronous, you'll need to pass a callback to the increment function so that when the count is returned from the database, the code can call the 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 es 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...
});

(I don't understand what the variables you've used mean or why they're not used later, so I just did a bit of a clean-up. Variables are scoped to function blocks and hoisted to the function, so you don't need to redeclare them in each if block like you had done with vio_val).

You could use the 'async' module. It makes the code a lot cleaner and easier to debug. Take a look at the code in GitHub for adduser.js & deleteuser.js in the following post

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

Regards Ganesh

length give you count of result array

  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);
发布评论

评论列表(0)

  1. 暂无评论