我在shell中找到了一些列出集合的答案,但我发现所有在nodejs脚本中列出集合的答案似乎都被弃用了,像collectionNames
和moongose.connection.db
等答案会返回没有方法。
我在shell中找到了一些列出集合的答案,但我发现所有在nodejs脚本中列出集合的答案似乎都被弃用了,像collectionNames
和moongose.connection.db
等答案会返回没有方法。
listCollections
获取包含所有集合信息的游标。然后,您可以调用游标上的toArray
函数来检索信息。db.listCollections().toArray(function(err, collInfos) {
// collInfos is an array of collection info objects that look like:
// { name: 'test', options: {} }
});
以下是如何使用 Node.js 的 3.4 版本的 Mongo 驱动程序的完整示例:
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());
async/await
,那么将迭代器的 toArray
转换为 Promise 更加简洁,而不必使用回调函数。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());
toArray
定义的行中,我得到了 Expected ";" but found "toArray"
。 - Timo var resource=[];
var ob=db.getSiblingDB('working_db');
ob.getCollectionNames().forEach(function(doc){
var regex = /^word|word1|word2|word3/i;
var found = doc.match(regex);
if(found){
printjson(doc)
resource.push({ resource: { db: "working_db", collection: doc }, actions: [ "insert","find","remove","update"] })
}
});
use admin,
db.createRole(
{
role: "ROLE_NAME",
privileges: resource,
roles: [
{
role: "clusterMonitor",
db: "admin"
}
]
}
)
const collections = Object.keys(mongoose.connection.collections);
使用nodejs从mongoDB获取特定数据库中所有集合的列表
const myDb = mongoose.connection.useDb(<databaseName>);
let collList = await myDb.db.listCollections().toArray();
collList = collList.map(el => {
return el.name;
});