2011-01-10 57 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); 
}