繁体   English   中英

NodeJ:使用另一个集合的结果过滤mongo查询结果

[英]NodeJs: Filter mongo query results with results from another collection

我遇到一种情况,需要对mongo集合(A)的一组不同值执行逻辑,然后将结果保存到另一个集合(B)。 但是(A)的内容会随着时间而变化,因此我只想对(B)中没有相应文档的(A)中的那些文档执行逻辑。 由于不支持联接,因此我尝试在节点级别执行此操作。 我正在查询集合(A)中的所有项目,并使用findOne在集合(B)中查找相应的条目。 如果找到它,我想将其从数组中删除,但是我被卡住了,因为findOne使用了异步回调,该回调似乎不适用于数组filter方法。 有一个更好的方法吗:

function loadNewDocumentsFromDB(callback){
  db.collection('A', function(err, acollection){    
    bcollection.find().toArray(function(err, arr){
      if(arr){
        // toQuery is the global array to be used elsewhere
        toQuery = arr.map(function(config){
          transformed = 
          {
            args: config._id, // these args are a doc representing a unique entry in 'B'
            listings: config.value.id.split(',') // used by other functions
          };

          return transformed;
        })
        .filter(function(transformed){
          db.collection('B', function(err, bcollection){
          bcollection.findOne(transformed.args, function(err, doc){
            // I want these values returned from the filter function not the callback
            if(doc){
              return false; // want to remove this from list of toQuery
            }else{
              return true; // want to keep in my list
          });
        });
      }
      callback();
    });
  }); 
}

这就是我设法使其工作的方式:

function loadOptionsFromDB(callback){
  toQuery = [];
  db.collection('list', function(err, list){    
    db.collection('data', function(err, data){
      list.find().each(function(err, doc){
        if(doc){ 
          transformed = 
            {
              args: doc._id,
              listings: doc.value.id.split(',')
            };
          (function(obj){       
            data.findOne(obj.args, function(err, found){
              if(found){}
              else{
                toQuery.push(obj);
              }
            });
          })(transformed);
        }else{
      //Done finding
          setTimeout(callback, 20000);
        }
      });       
    });
  }); 
}

更好的方法是在数据库上执行此操作。 检查是否有两次执行http://docs.mongodb.org/manual/core/map-reduce/对您有用。 有关更多信息,请参见在MongoDB中合并两个集合。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM