【问题标题】:MongoDB: How to read all documents from all collections use expressjs?MongoDB:如何使用 expressjs 从所有集合中读取所有文档?
【发布时间】:2019-10-19 08:27:01
【问题描述】:

我有一个 mongodb,其中包含多个集合中的多个文档,我想遍历它的每个人。下面是我的代码,

const mongo = require('mongodb');
const url = 'mongodb://localhost:27017/test'

mongo.connect(url,{ useNewUrlParser: true },  data, (err, db)=>{
    console.log('connection success');

    db.db().listCollections().toArray(function(err, colls) {
        colls.forEach(element => {
            db.db().collection(element.name.toString()).find().toArray((err, doc) => {
                console.log(doc);
            });
        });
    });

    db.close();
})
}

这是我从 listCollections() 得到的结果

[ ....,
{ name: 'documetn1',
type: 'collection',
options: {},
info: { readOnly: false, uuid: [Binary] },
idIndex:
 { v: 2, key: [Object], name: '_id_', ns: 'test.documetn1' } }, 
...]

不知怎的,我在下面得到了空值

db.db().collection(element.name.toString()).find().toArray((err, doc) => {
                    console.log(doc);
                });

在这里需要帮助!

【问题讨论】:

  • 打印 element.name.toString() 并检查输出是什么。
  • 也许更重要:打印err

标签: node.js mongodb express


【解决方案1】:

我已经尝试了您的代码,每个集合都在 err"MongoError: Topology was destroyed" 找到返回。正如 Carlos Rodríguez 在this answer to a question related to this error 中所说的那样,这似乎是由于早期的db.close() 所以可以修复这样做,例如:

const mongo = require('mongodb');
const url = 'mongodb://localhost:27017/test'

mongo.connect(url, { useNewUrlParser: true },  data, (err, db) => {
    console.log('connection success');

    db.db().listCollections().toArray((err, colls) => {
        var collsPrinted = 0;
        colls.forEach(element => {
            db.db().collection(element.name).find().toArray((err, doc) => {
                console.log(doc);
                if (++collsPrinted == colls.length) db.close();
            });
        });
    });
})

【讨论】:

  • 不管怎样,我不知道你想这样做是为了什么,我希望这是一个小型数据库上的开发过程,因为我认为打印所有的元素并不是一个好主意数据库中的集合。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-09
  • 2021-03-30
  • 1970-01-01
  • 2017-09-14
  • 1970-01-01
相关资源
最近更新 更多