Exporting modules that require asynchronous setup code

I wanted to create a single instance of a MongoClient and then export the db object so that I could import it throughout my project. But the problem is that it requires some asynchronous to create the db object. So you can't export the object until after the asynchronous code completes.

Here's the solution I found:

const { MongoClient } = require('mongodb');

module.exports = (async function() {
    const client = await MongoClient.connect(
        process.env.MONGO_URL, 
        { minPoolSize: 2, maxPoolSize: 10 }
    );
    const db = client.db(process.env.MONGO_DBNAME);
    return db;
})();

When I first looked at this code I worried that it would create a new db object every time the module was imported. But, it's actually a self-invoking function that can only be invoked one time. So there will only be a single db object created.

Here's the code to import the db object:

const db = await require('./db');

But, because this code is using await, it must be wrapped inside an async function. I was able to get around this, but as I understand, new versions of Node will allow you to use await without async when initializing apps. We'll see...