2011-01-10 5 views
1

私はJSの方が一般的ですが、MongoDBからいくつかのデータを照会しようとしています。基本的に、私の最初のクエリは、指定されたセッションIDを持つセッションの情報を取得します。 2番目のクエリは、指定された場所に近い場所にあるドキュメントの単純なジオスペースクエリを実行します。nodejs、mongodb - 複数のクエリのデータを操作するにはどうすればよいですか?

私はmongodb-native javascriptドライバを使用しています。これらのクエリメソッドはすべて、結果をコールバックで返します。したがって、それらは非ブロッキングです。これは私のトラブルの根源です。私がする必要があるのは、2番目のクエリの結果を取得し、返されたすべてのドキュメントのsessionIdの配列を作成することです。それから私はそれらを後で関数に渡すつもりです。しかし、私はこの配列を生成することはできませんし、コールバックの外のどこでも使用します。

これを正しく行う方法を知っている人はいますか?

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

機能は、スコープを「囲む」唯一のものです。

これは、内部コールバック関数の変数項目が外側スコープでアクセスできないことを意味します。

それは、すべての内部のものに表示されますので、あなたは外側のスコープで変数を定義することができます:あなたのコードがそれに一致するように記述する必要がありますので

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); 
} 
関連する問題