'How to Wait Until a MongoDB Connection is Made before Using the Database

I have the following code to create a connection to my MongoDB database, and to store it for future use.

const mongodb = require('mongodb');
const MongoClient = mongodb.MongoClient;

// The database will be defined once a connection to between the cluster and mongodb is created
let _database;

const uri = '';
const databaseName = 'db';

const mongoConnect = () => {
    MongoClient.connect(uri)
        .then((client) => {
            _database = client.db(databaseName);
        })
        .catch((err) => {
            console.log(err);
            throw err;
        });
};

const getDb = () => {
    if (_database) {
        return _database;
    }
    throw 'No database found!';
};

module.exports = {
    mongoConnect,
    getDb
}

My problem is that _database is undefined until the connection is made. If my website tries to use the database before _database is defined it will throw an error and crash.

I want to make it so instead of crashing, other portions of my code would just wait until _database is not undefined. Sounds like a await/async solution is needed, but I can't wrap my head around how to approach implementing something like that here. Any advice would be great!



Solution 1:[1]

**Pretty Simple approach ** Just add await before MongoClient.connect function and make function async Now It will wait for the connection to have response then move forward.

const mongodb = require('mongodb');
const MongoClient = mongodb.MongoClient;

// The database will be defined once a connection to between the cluster 
and mongodb is created
let _database;

const uri = 'mongodb://localhost:27017/mydb';
const databaseName = 'db';

const mongoConnect = async () => {
await MongoClient.connect(uri)
    .then((client) => {
        _database = client.db(databaseName);
    })
    .catch((err) => {
        console.log(err);
        throw err;
    });
 };

const getDb = () => { 
  if (_database) {
    return _database;
}
throw 'No database found!'; 
};



module.exports = {
  mongoConnect,
  getDb
}

Solution 2:[2]

Embedding AWS credentials on any client-side apps is a scary idea. In order to solve this challenge, you would have to use either CloudFront or S3 Signed URLs.

This approach requires the generation of short-lived upload/download URLs in one of your APIs so that it could send back to the client-application a URL where we can directly upload/download assets to/from an S3 bucket.

It allows us to avoid the hardcoding of AWS credentials on client-applications and have dynamic short-lived URLs dedicated for one-time upload/download operations on-demand.

It shouldn't be that hard and you could follow this tutorial to learn more about S3 signed urls.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Shamoon97
Solution 2 Allan Chua