【发布时间】:2021-10-04 21:49:12
【问题描述】:
我试图在http://mongodb.github.io/node-mongodb-native/中找到解决这个问题的方法
但是,我找不到从 Node.js 应用程序列出所有可用 MongoDB 数据库的解决方案。
【问题讨论】:
-
我认为你不能用
mongodb-native来做到这一点
我试图在http://mongodb.github.io/node-mongodb-native/中找到解决这个问题的方法
但是,我找不到从 Node.js 应用程序列出所有可用 MongoDB 数据库的解决方案。
【问题讨论】:
mongodb-native来做到这一点
【讨论】:
您现在可以使用 Node Mongo 驱动程序(使用 3.5 测试)完成此操作
const MongoClient = require("mongodb").MongoClient;
const url = "mongodb://localhost:27017/";
const client = new MongoClient(url, { useUnifiedTopology: true }); // useUnifiedTopology removes a warning
// Connect
client
.connect()
.then(client =>
client
.db()
.admin()
.listDatabases() // Returns a promise that will resolve to the list of databases
)
.then(dbs => {
console.log("Mongo databases", dbs);
})
.finally(() => client.close()); // Closing after getting the data
【讨论】:
只有管理员可以查看所有数据库。因此,使用管理员凭据连接到 mongodb 数据库,然后通过 await db.admin() 创建一个管理员实例,然后列出所有数据库 await adminDB.listDatabases()
const MongoClient = require('mongodb').MongoClient;
let client = await MongoClient.connect(process.env.MONGO_DB_URL);
const db = await client.db(process.env.DEFAULT_DB_NAME);
let adminDB = await db.admin();
console.log(await adminDB.listDatabases());
【讨论】:
*db.admin().listDatabases 很难获取列表,下面的代码在nodejs中可以正常工作*
const { promisify } = require('util');
const exec = promisify(require('child_process').exec)
async function test() {
var res = await exec('mongo --eval "db.adminCommand( { listDatabases: 1 }
)" --quiet')
return { res }
}
test()
.then(resp => {
console.log('All dbs', JSON.parse(resp.res.stdout).databases)
})
test()
【讨论】: