Share connected DB instance to other files

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

Hi @HSD_Qatar, there are many possible ways to pass the connection instance between files. One of the cleanest and very modern approach is as follows:

const { MongoClient } = require('mongodb');
const config = require('./config');
const Users = require('./Users');
const conf = config.get('mongodb');

class MongoBot {
  constructor() {
    const url = `mongodb://${conf.hosts.join(',')}`;

    this.client = new MongoClient(url, conf.opts);
  }
  async init() {
    await this.client.connect();
    console.log('connected');

    this.db = this.client.db(conf.db);
    this.Users = new Users(this.db);
  }
}

module.exports = new MongoBot();

and you can require() the same into another file.

You can learn more about this here.

In case you have any doubts, please feel free to reach out to us.

Thanks.
Sourabh Bagrecha,
Curriculum Services Engineer

2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.