Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

331
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda