循环同步

时间:2016-09-04 09:17:41

标签: javascript node.js mongodb

MongoClient.connect('mongodb://127.0.0.1:27017/manufacturers', 
  function(err, db) {
    db.listCollections().toArray(function(err, collections) {
      for (var key in collections) { // iterate over all collections
        var manufacturer = collections[key]['name'];
        var query = {}; // and get all documents
        findDocuments(db, manufacturer, query, processData);
      }
    });
  });

var findDocuments = function(db, collection, queryObj, callback) {
  var cursor = db.collection(collection).find(queryObj);
  cursor.each(function(err, docs) {
    if (docs != null) { console.log(docs); }
  });
}

..它有效但只能从其中一个集合中获取数据,而不是全部。

似乎for循环立即结束,如何让它等到中间函数返回?

1 个答案:

答案 0 :(得分:1)

For循环同步运行,你需要的是一个函数。 我创建了一个具有以下结构的示例数据库,

manufacturers (db)
  man1 (collection 1)
   man1doc1
   man1doc2
  man2 (collection 2)
   man2doc1

并运行以下代码,按顺序打印所有集合中的所有文档,一次打印一个集合。

var MongoClient = require('mongodb').MongoClient;

MongoClient.connect('mongodb://127.0.0.1:27017/manufacturers', 
function(err, db) {
db.listCollections().toArray(function(err, collections) {

  if(!collections.length){
    console.log('No collections found');
    return;
  }

  function sequentialIterate(key){
    if(key === collections.length){
      console.log('All documents in all collections printed');
      return;
    }
    var manufacturer = collections[key]['name'];
    var query = {};

    db.collection(manufacturer).find(query, function(err, cursor){
       cursor.each(function(err, doc){
        if(doc){
          console.log(doc);
        }
        else{
          console.log('All documents in collection ' + manufacturer + ' printed');
          sequentialIterate(key + 1);
        }
      });
    });       
  };

  sequentialIterate(0); // kick things off

 });
});

打印出以下内容:

{ _id: 57cc44fc03b65f4084865057, name: 'man2doc1' }
All documents in collection man2 printed
{ _id: 57cc44f003b65f4084865055, name: 'man1doc1' }
{ _id: 57cc44f303b65f4084865056, name: 'man1doc2' }
All documents in collection man1 printed
All documents in all collections printed

如果需要,可以使用回调替换console.log()。