1

I have initialized the connection to my mongodb and now export the db to other nodejs files. How can I do that?

i thought of something like this but it is giving errors.

let database;
export const connectDB = async () => {
  const client = new MongoClient(config.dbUri, {
    useUnifiedTopology: true,
  });

  try {
    await client.connect();
    database = client.db('azkaben');
    logger.info('Connected to Database');
  } catch (e) {
    logger.error(e);
  } finally {
    await client.close();
  }
};

export default database

Error : undefined value of database

1 Answer 1

1

database will always be null when you import it.

connectDB is aync call by the time it executes your database variable is already loaded as null.

connectDB you can return database from here.

export const connectDB = async () => {
  const client = new MongoClient(config.dbUri, {
    useUnifiedTopology: true,
  });

  try {
    await client.connect();
    database = client.db('azkaben');
    return database; // you can get from here
    logger.info('Connected to Database');
  } catch (e) {
    logger.error(e);
  } finally {
    await client.close();
  }
};

Updated code
export const connectDB = async () => {
  if (database) return database; // return if database already connected. 
  const client = new MongoClient(config.dbUri, {
    useUnifiedTopology: true,
  });

  try {
    await client.connect();
    database = client.db('azkaben');
    return database; // you can get from here
    logger.info('Connected to Database');
  } catch (e) {
    logger.error(e);
  } finally {
    await client.close();
  }
};
Sign up to request clarification or add additional context in comments.

4 Comments

But, if i will do that , I have to connect to database every time I import that db
@anitashrivastava In that case you can use const getDatabse = async() => databse; function to get the value, but you need to make sure the application is connected to database 1st after that your code execution starts. getDatabse().then(db => query).
@anitashrivastava or you can even use const getDatabse => databse; but sure your database is connected before you call getDatabse.
@anitashrivastava updated answer with 1 more option.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.