How do I share my connected DB instance to my other files.
For example I open a DB connection in my main index.js file and instead of re-opening the connection again & again in other files, I want to share this instance of connected db to my other files
For Example, after the import statements, I write the following in my index file
const connectionClient = new MongoClient(configs.db_url_live, { useUnifiedTopology: true })
let dbConnection;
let connectedDb;
(async () => {
dbConnection = await connectionClient.connect();
connectedDb = dbConnection.db(configs.db_name);
console.log(‘Connectd to DB from garageServer');
})();
Now I use this statement at the end of my file
module.exports=connectedDb;
And in my file where I need that instance, I use this statement
import * as all from “./index”;
But there are two problem in my this approach
First of all I get this error in my other file where I am requiring the connected DB instance
Cannot use import statement outside a module
Secondly, even I somehow get rid of this error, the main problem is,
When importing my instance from index file, it is undefined, because it is not connected initially but export statement is already executed.
How do I make this happen.
Thanks in advance to helping hands