NodeJS/Mongo:通过各种集合循环查询 [英] NodeJS/Mongo: Looping a query through various collections

查看:91
本文介绍了NodeJS/Mongo:通过各种集合循环查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望使用示例代码"findOne"文档,以便在各种收藏夹"中插入一堆文档:

I'm looking to loop a query through various collection with MongoDB using the NodeJS Driver. For this test, I've used the sample code from the 'findOne' docs to insert a bunch of documents in various Collections:

  collection.insertMany([{a:1, b:1}, {a:2, b:2}, {a:3, b:3}], {w:1}, function(err, result) {
    test.equal(null, err);

同时创建各种集合(每个集合至少有一个先前插入的文档实例):

Creating at the same time various collections (each collection has at least one instance of the documents previously inserted):

  • 测试
  • test1
  • test2
  • test3
  • test4
  • test6
  • test10

我想要的是收集数据库中我拥有的收藏夹列表(在我的情况下为'test'):

And what I want is to gather the list of collection that I have in the DB ('test' in my case):

var MongoClient = require("mongodb").MongoClient,
  test = require("assert");
MongoClient.connect("mongodb://localhost:27017/test", function(err, db) {
  db.listCollections().toArray(function(err, items) {
    test.ok(items.length >= 1);
    console.log(items);
    db.close();
  });
});

然后弹出前面提到的收藏列表.到目前为止,一切都很好!我什至可以遍历数组以仅获取集合的名称:

And there pops the list of collection previously mentioned. Up until now everything is all-right! I can even loop through the array to get the name of the collections only:

var MongoClient = require("mongodb").MongoClient,
  test = require("assert");
MongoClient.connect("mongodb://localhost:27017/test", function(err, db) {
  db.listCollections().toArray(function(err, items) {
    test.ok(items.length >= 1);
    items.forEach(c => {
      console.log(c.name);
    });
    db.close();
  });
});

再次没有问题!但是当我在循环内尝试查询时:

Again no problem there! But when I then try a query within the loop:

var MongoClient = require("mongodb").MongoClient,
  test = require("assert");
MongoClient.connect("mongodb://localhost:27017/test", function(err, db) {
  db.listCollections().toArray(function(err, items) {
    test.ok(items.length >= 1);
    items.forEach(c => {
      var collection = db.collection(c.name);
      collection.findOne({ a: 2 }, { fields: { b: 1 } }, function(err, doc) {
        console.log(doc);
      });
    });
  });
  db.close();
});

我得到:

null
null
null
null
null
null
null

即使通过循环获取该集合似乎也可以很好地工作:

Even though looping through to get the collection seems to work perfectly fine:

var MongoClient = require("mongodb").MongoClient,
  test = require("assert");
MongoClient.connect("mongodb://localhost:27017/test", function(err, db) {
  db.listCollections().toArray(function(err, items) {
    test.ok(items.length >= 1);
    items.forEach(c => {
      var collection = db.collection(c.name);
      console.log(collection);
      });
    });
  db.close();
});

示例输出:

Collection {
  s: 
   { pkFactory: 
      { [Function: ObjectID]
        index: 10866728,
        createPk: [Function: createPk],
        createFromTime: [Function: createFromTime],
        createFromHexString: [Function: createFromHexString],
        isValid: [Function: isValid],
        ObjectID: [Circular],
        ObjectId: [Circular] },
     db: 
      Db {
        domain: null,
        _events: {},
        _eventsCount: 0,
        _maxListeners: undefined,
        s: [Object],
        serverConfig: [Getter],
        bufferMaxEntries: [Getter],
        databaseName: [Getter] },
     topology: 
      Server {
        domain: null,
        _events: [Object],
        _eventsCount: 8,
        _maxListeners: undefined,
        clientInfo: [Object],
        s: [Object] },
     dbName: 'test',
     options: 
      { promiseLibrary: [Function: Promise],
        readConcern: undefined,
        readPreference: [Object] },
     namespace: 'test.test2',
     readPreference: 
      ReadPreference {
        _type: 'ReadPreference',
        mode: 'primary',
        tags: undefined,
        options: undefined },
     slaveOk: true,
     serializeFunctions: undefined,
     raw: undefined,
     promoteLongs: undefined,
     promoteValues: undefined,
     promoteBuffers: undefined,
     internalHint: null,
     collectionHint: null,
     name: 'test2',
     promiseLibrary: [Function: Promise],
     readConcern: undefined } }

我猜想Collection结构是我循环的问题,但是我不确定到底发生了什么... 这是每个集合的预期输出的示例:

I'm guessing that the Collection structure is the problem for my loop but I'm not sure what's happening exactly... This is an example of the expected output for each Collection:

{ _id: 5a13de85a55e615235f71528, b: 2 }

任何帮助将不胜感激!提前致谢!

Any help would be much appreciated! Thanks in advance!

推荐答案

尽管不是最佳语法,并且除了记录输出外没有用,但这确实对我有用:

Though not the best syntax and useless except for logging output, this does work for me:

var mongodb = require('mongodb');


mongodb.connect('mongodb://localhost:27017/test', function (err, db) {
    if (err) {
        throw err;
    }

    db.listCollections().toArray(function (err, cols) {
        if (err) {
            throw err;
        }

        cols.forEach(function (col) {
            db.collection(col.name).find({}, {}, 0, 1, function (err, docs) {
                if(err){
                    throw err;
                }
                console.log(col);
                docs.forEach(console.log);
            });
        });
    })
})

那么,查询条件可能不匹配吗?

So, perhaps the query conditions don't match anything ?

此外,对Promises更好:

Also, better with Promises:

const mongodb = require('mongodb');
const Promise = require('bluebird');

function getDb() {
    return Promise.resolve(mongodb.connect('mongodb://localhost:27017/test'));
}

function getCollections(db) {
    return Promise.resolve(db.listCollections().toArray());
}

function getDocs(db, col) {
    return Promise.resolve(db.collection(col.name).find({},{},0,1).toArray());
}

const data = {};
getDb()
.then((db) => {
    data.db = db;
    return getCollections(db);
}).then((cols) => {
    data.cols = cols;
    return Promise.map(cols, (col) => getDocs(data.db,col));
}).then((docs) => {
    console.log(docs);
})

这篇关于NodeJS/Mongo:通过各种集合循环查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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