nodejs,mongodb-如何处理来自多个查询的数据? [英] nodejs, mongodb - How do I operate on data from multiple queries?

查看:429
本文介绍了nodejs,mongodb-如何处理来自多个查询的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一般来说,我是JS的新手,但是我试图从MongoDB查询一些数据.基本上,我的第一个查询将检索具有指定会话ID的会话的信息.第二个查询对位置在指定位置附近的文档进行简单的地理空间查询.

I'm new to JS in general, but I am trying to query some data from MongoDB. Basically, my first query retrieves information for the session with the specified session id. The second query does a simple geospacial query for documents with a location near the specified location.

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

I'm using the mongodb-native javascript driver. All of these query methods return their results in callbacks, so they're non-blocking. This is the root of my troubles. What I'm needing to do is retrieve the results of the second query, and create an Array of sessionIds of all the returned documents. Then I'm going to pass those to a function later. But, I can't generate this array and use it anywhere outside the callback.

有人知道如何正确地做到这一点吗?

Does anyone have any idea how to properly do this?

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);
    });
  });
});

推荐答案

函数是javascript中唯一包围"作用域的东西.

Functions are the only thing on javascript that "enclose" scope.

这意味着内部回调函数中的变量项无法在外部作用域上访问.

This means that the variable items in your inner callback function are not accessible on the outer scope.

您可以在外部作用域中定义一个变量,以便对所有内部变量均可见:

You can define a variable in the outer scope so it will be visible to all the inner ones:

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();
         });
       });
     });
   });
}

这篇关于nodejs,mongodb-如何处理来自多个查询的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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