node.jsmongodbnode-mongodb-native

Mongodb native connections from nodejs return undefined databases list


I'm just starting to use Mongodb without mongoose (to get away from the schemas), and wanted to create a simple module with various exported functions to use in the rest of my app. I've pasted the code below.

The problem I'm having is that the databasesList.databases comes back as undefined, and I'm not sure why. There should be 2 databases on my cluster, and one collection in each database.

As a tangential question, I thought maybe I would check the collections instead (now commented out), but though I found this page (https://docs.mongodb.com/manual/reference/method/db.getCollectionNames/) the function getCollectionNames seems not to exist. Now I'm wondering if I'm using the wrong documentation and that is why my databases are coming back undefined.

const client = new MongoClient(uri)
const connection = client.connect( function (err, database) {
    if (err) throw err;
    else if (!database) console.log('Unknown error connecting to database');
    else {
        console.log('Connected to MongoDB database server');
    }

});

module.exports = {
    getDatabaseList: function() {
        console.log('start ' + client);

        databasesList = client.db().admin().listDatabases();
        //collectionList = client.db().getCollectionNames();
        //console.log("Collections: " + collectionList);
    
        console.log("Databases: " + databasesList.databases);
        //databasesList.databases.forEach(db => console.log(` - ${db.name}`));
    }
}```

Solution

  • your code is correct Just need to change few things.

    module.exports = {
        getDatabaseList: async function() {
            console.log('start ' + client);
    
            databasesList = await client.db().admin().listDatabases();
            //collectionList = await client.db().getCollectionNames();
            //console.log("Collections: " + collectionList);
        
            console.log("Databases: " + databasesList.databases);
            databasesList.databases.forEach(db => console.log(` - ${db.name}`));
        }
    }
    

    You have to declare async function and use await also.

    The async and await keywords enable asynchronous, promise-based behaviour to be written in a cleaner style, avoiding the need to explicitly configure promise chains.