处理异步数据库查询中的Node.js和MongoDB [英] Handling asynchronous database queries in node.js and mongodb

查看:119
本文介绍了处理异步数据库查询中的Node.js和MongoDB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个问题与node.js中查询MongoDB的异步这里是我的code

I have this issue with querying mongodb asynchronously from node.js. Here is my code

var values = [];
var positives = new Array();
var negatives = new Array();

var server1 = new mongodb.Server('localhost',27017, {auto_reconnect: true});
var db1 = new mongodb.Db('clicker', server1);   

db1.open(function(err, db) {
    if(!err) {

        db1.collection('feedback', function(err, collection) {
            for (var i=0;i <5; i++) {
                collection.find(
                    {value:1},
                    {created_on: 
                        {       
                            $gte:startTime + (i*60*1000 - 30*1000),
                            $lt: startTime + (i*60*1000 + 30*1000)
                        }
                    },
                    function(err_positive, result_positive) {
                        result_positive.count(function(err, count){
                                console.log("Total matches: " + count);
                                positives[i] = count;
                        });
                    }

                );              

                collection.find(
                    {value:0},
                    {created_on: 
                        {
                            $gte:startTime + (i*60*1000 - 30*1000),
                            $lt: startTime + (i*60*1000 + 30*1000)
                        }
                    },
                    function(err_negative, result_negative) {
                        result_negative.count(function(err, count){
                                console.log("Total matches: " + count);
                                negatives[i] = count;
                        });
                    }   
                );                                  
            }

        });

    } else {
        console.log('Error connecting to the database');
    }      

});

其实,我试图从数据库中获取某些值。然后我需要处理这些值。这只是我需要从正数减去负计数,然后初始化值数组positivecount负计数。现在,因为结果是异步获得。我怎么来处理这些值,并把它们的数值数组

Actually, I am trying to get some values from the database. And then I need to manipulate these values. It's just that I need to subtract negative count from positive count and then initialize the value array with positivecount-negative count. Now since the results are obtained asynchronously. How am I supposed to manipulate those values and put them in the values array.

推荐答案

在我进一步解释,我想指出,有一个在您code错误:

Before I explain further, I'd like to note that there is a bug in your code:

function(err_positive, result_positive) {
    result_positive.count(function(err, count){
        console.log("Total matches: " + count);
        positives[i] = count;  // <--- BUG: i id always 5 because it
    });                        //           is captured in a closure
}

经典倒闭和放大器;循环问题。参见:<一href=\"http://stackoverflow.com/questions/3572480/please-explain-the-use-of-javascript-closures-in-loops/3572616#3572616\">Please讲解使用循环中的JavaScript闭包

现在,如何在循环处理异步功能。其基本思想是,你需要跟踪多少异步调用已经完成并运行code一旦最终调用返回。例如:

Now, how to handle asynchronous functions in loops. The basic idea is that you need to keep track of how many asynchronous calls have completed and run your code once the final call returns. For example:

var END=5;
var counter=end;
for (var i=0;i<END; i++) {
  collection.find(
    {value:1},
    {created_on: 
      {       
        $gte:startTime + (i*60*1000 - 30*1000),
        $lt: startTime + (i*60*1000 + 30*1000)
      }
    },
    (function(j){
      return function(err_positive, result_positive) {
        result_positive.count(function(err, count){
            console.log("Total matches: " + count);
            positives[j] = count;
        });

        counter--;
        if (!counter) {
          /*
           * Last result, now we have all positives.
           *
           * Add code that need to process the result here.
           *
           */
        }
      }
    })(i)
  ); 
}

但是,如果我们继续这样做,很明显,我们最终创造了一堆临时变量,并与可怕的嵌套code结束。但是,这是JavaScript的,我们可以封装逻辑函数中的这种模式。这里是我实施JavaScript本等参加的所有对完成的逻辑:<一href=\"http://stackoverflow.com/questions/4631774/coordinating-parallel-execution-in-node-js/4631909#4631909\">Coordinating并行执行在node.js中

但是,由于我们使用Node.js的,我们可以使用便捷的异步模块形式NPM: https://npmjs.org/package /异步

But since we're using node.js, we can use the convenient async module form npm: https://npmjs.org/package/async

使用异步,你可以写你的code是这样的:

With async, you can write your code like this:

var queries = [];

// Build up queries:
for (var i=0;i <5; i++) {
  queries.push((function(j){
    return function(callback) {
      collection.find(
        {value:1},
        {created_on: 
          {       
            $gte:startTime + (j*60*1000 - 30*1000),
            $lt: startTime + (j*60*1000 + 30*1000)
          }
        },
        function(err_positive, result_positive) {
          result_positive.count(function(err, count){
            console.log("Total matches: " + count);
            positives[j] = count;          
            callback();
          });
        }

      );
    }
  })(i));
  queries.push((function(j){
    return function(callback) {
      collection.find(
        {value:0},
        {created_on: 
          {
            $gte:startTime + (j*60*1000 - 30*1000),
            $lt: startTime + (j*60*1000 + 30*1000)
          }
        },
        function(err_negative, result_negative) {
          result_negative.count(function(err, count){
            console.log("Total matches: " + count);
            negatives[j] = count;
            callback();
          });
        }   
      );
    }
  })(i));  
}

// Now execute the queries:
async.parallel(queries, function(){
  // This function executes after all the queries have returned
  // So we have access to the completed positives and negatives:

  // For example, we can dump the arrays in Firebug:
  console.log(positives,negatives);
});

这篇关于处理异步数据库查询中的Node.js和MongoDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆