【问题标题】:nodejs, mongodb - How do I operate on data from multiple queries?nodejs, mongodb - 如何对来自多个查询的数据进行操作?
【发布时间】:2011-06-06 07:27:48
【问题描述】:

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

我正在使用 mongodb-native 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);
    });
  });
});

【问题讨论】:

    标签: javascript mongodb node.js


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-03
        • 2014-12-01
        • 2011-01-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多