Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting list of all databases with Mongoose

There are some similar questions but all of them involves using the MongoDB NodeJS driver instead of Mongoose ODM.

I read the docs but couldn't find such functionality.

like image 980
jviotti Avatar asked Feb 11 '13 23:02

jviotti


2 Answers

You can't directly get the list from the connection provided by mongoose, but it's easy to do with the mongo Admin object as it contains a function called 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;    
    });
});
like image 158
WiredPrairie Avatar answered Oct 04 '22 05:10

WiredPrairie


A very modern approach to get list of all mongo databases using mongoose (version 6.10.*) is to Create a mongoose connection to connect to Mongo's admin database and make sure you have an admin user.

Mongoose object is a very complex object. To list the db's :

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
    });
})

Result:

{ 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 }
like image 32
Arun Panneerselvam Avatar answered Oct 04 '22 07:10

Arun Panneerselvam