在 nodejs 脚本中列出 mongo 数据库中的所有集合
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30470415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Listing all collections in a mongo database within a nodejs script
提问by Jake
I have found a few answers for listing collections in the shell but all the answers I have found for listing collections in a nodejs script seem to have been deprecated, answers like collectionNamesand moongose.connection.dbreturn has no method.
我找到了一些在 shell 中列出集合的答案,但是我找到的在 nodejs 脚本中列出集合的所有答案似乎都已被弃用,像collectionNames和moongose.connection.dbreturn这样的答案没有任何方法。
回答by JohnnyHK
In the 2.0 version of the MongoDB driver for node.js you can use listCollectionsto get a cursor that contains the information of all collections. You can then call toArrayon the cursor to retrieve the info.
在 node.js 的 MongoDB 驱动程序的 2.0 版本中,您可以使用listCollections获取包含所有集合信息的游标。然后您可以调用toArray光标来检索信息。
db.listCollections().toArray(function(err, collInfos) {
// collInfos is an array of collection info objects that look like:
// { name: 'test', options: {} }
});
回答by John Alexis Guerra Gómez
Here is a full example on how you do it with the 3.4 version of the Mongo driver for node
这是一个完整的示例,说明如何使用 3.4 版本的 Mongo 驱动程序进行 node
const MongoClient = require("mongodb").MongoClient;
// Connection url
var url = 'mongodb://localhost:27017/test';
const client = new MongoClient(url, { useUnifiedTopology: true }); // { useUnifiedTopology: true } removes connection warnings;
const dbName = "test";
client
.connect()
.then(
client =>
client
.db(dbName)
.listCollections()
.toArray() // Returns a promise that will resolve to the list of the collections
)
.then(cols => console.log("Collections", cols))
.finally(() => client.close());
回答by Steven Spungin
If you have access to async/await, it is much cleaner to promisify toArrayon the iterator and not use a callback.
如果您有权访问async/await,则toArray在迭代器上进行承诺而不使用回调会更清晰。
static toArray(iterator) {
return new Promise((resolve, reject) => {
iterator.toArray((err, res) => {
if (err) {
reject(err);
} else {
resolve(res);
}
});
});
}
const myArray = await toArray(db.listCollections());

