Node.js Async/Await module export

You have to export synchronously, so its impossible to export client and db directly. However you could export a Promise that resolves to client and db:

module.exports = (async function() {
 const client = await MongoClient.connect(url, {
   useNewUrlParser: true
 });

  const db = client.db(mongo_db);
  return { client, db };
})();

So then you can import it as:

const {client, db} = await require("yourmodule");

(that has to be in an async function itself)

PS: console.error(err) is not a proper error handler, if you cant handle the error just crash

Leave a Comment