2011-01-10 59 views
1

我是JS的新手,但我试图从MongoDB中查询一些数据。基本上,我的第一个查询检索具有指定会话ID的会话的信息。第二个查询对位于指定位置附近的文档进行简单的地理空间查询。nodejs,mongodb - 如何操作来自多个查询的数据?

我正在使用mongodb原生javascript驱动程序。所有这些查询方法都以回调的形式返回结果,因此它们是非阻塞的。这是我的烦恼的根源。我需要做的是检索第二个查询的结果,并创建所有返回文档的sessionIds数组。然后我将在稍后将这些函数传递给函数。但是,我无法生成这个数组并在回调之外的任何地方使用它。

有没有人有任何想法如何正确地做到这一点?

db.collection('sessions', function(err, collection) { 
    collection.findOne({'sessionId': client.sessionId}, function(err, result) { 
    collection.find({'geolocation': {$near: [result.geolocation.latitude, result.geolocation.longitude]}}, function(err, cursor) { 
     cursor.toArray(function(err, item) { 

     console.log(item); 
    }); 
    }); 
}); 

回答

6

函数是javascript中“唯一”范围的函数。

这意味着内部回调函数中的变量项在外部范围内不可访问。

您可以定义在外部范围的变量所以这将是可见的所有内部的:

function getItems(callback) { 
    var items; 

    function doSomething() { 
    console.log(items); 
    callback(items); 
    } 

    db.collection('sessions', function(err, collection) { 
    collection.findOne({'sessionId': client.sessionId}, function(err, result) { 
     collection.find({'geolocation': {$near: [result.geolocation.latitude, result.geolocation.longitude]}}, function(err, cursor) { 
     cursor.toArray(function(err, docs) { 
      items = docs; 
      doSomething(); 
     }); 
     }); 
    }); 
    }); 
} 
0

的Node.js是异步的,因此您的代码应写入与之匹敌。

我发现此模型很有用。每个嵌套的回调混杂都包含在助手函数中,该函数使用错误代码和结果调用参数回调'next'。

function getSessionIds(sessionId, next) { 
    db.collection('sessions', function(err, collection) { 
     if (err) return next(err); 
     collection.findOne({sessionId: sessionId}, function(err, doc) { 
      if (err) return next(err); 
      if (!doc) return next(false); 
      collection.find({geolocation: {$near: [doc.geolocation.latitude, result.geolocation.longitude]}}.toArray(function(err, items) { 
       return next(err, items); 
      }); 
     }); 
    }); 
} 
在调用代码

然后

getSessionIds(someid, _has_items); 
function _has_items(err, items) { 
    if(err) // failed, do something 
    console.log(items); 
}