Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

321
Views
How to export mongodb db collections to another js file?

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

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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();
  }
};
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!