有一些类似的问题,但所有问题都涉及使用MongoDB NodeJS driver代替Mongoose ODM。
我看了the docs但找不到这样的功能。
答案 0 :(得分:10)
你不能直接从mongoose提供的连接中获取列表,但是使用mongo Admin
对象很容易,因为它包含一个名为listDatabases
的函数:
var mongoose = require('mongoose')
, Admin = mongoose.mongo.Admin;
/// create a connection to the DB
var connection = mongoose.createConnection(
'mongodb://user:pass@localhost:port/database');
connection.on('open', function() {
// connection established
new Admin(connection.db).listDatabases(function(err, result) {
console.log('listDatabases succeeded');
// database list stored in result.databases
var allDatabases = result.databases;
});
});
答案 1 :(得分:1)
使用mongoose(版本6.10。*)获取所有mongo数据库列表的一种非常现代的方法是 创建一个mongoose连接以连接到Mongo的管理数据库 ,并进行确保您具有管理员用户。
猫鼬对象是一个非常复杂的对象。列出数据库:
const connection = `mongodb://${encodeURIComponent(username)}:${encodeURIComponent(password)}@${hostname}:${port}/admin`
mongoose is a very complex object with promises for executing several functions. to list the db's :
mongoose.connect(connection, { useNewUrlParser: true , useUnifiedTopology: true })
.then( (MongooseNode) => {
/* I use the default nativeConnection object since my connection object uses a single hostname and port. Iterate here if you work with multiple hostnames in the connection object */
const nativeConnetion = MongooseNode.connections[0]
//now call the list databases function
new Admin(nativeConnetion.db).listDatabases(function(err, results){
console.log(results) //store results and use
});
})
结果:
{ databases:
[ { name: 'admin', sizeOnDisk: 184320, empty: false },
{ name: 'config', sizeOnDisk: 73728, empty: false },
{ name: 'local', sizeOnDisk: 73728, empty: false },
{ name: 'test', sizeOnDisk: 405504, empty: false } ],
totalSize: 737280,
ok: 1 }
答案 2 :(得分:-1)