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

181
Vistas
Is it okay to declare the db instance as a global variable for accessible at all the time , without need to use "require" statement in node js

I am a beginner in "node js" I am developing an program and I want to use the database model in all For example (something like "wpdb") WordPress Is the best way to create it as a global variable, or to use the require statement as needed?

Please help me get the best answer. Thanks

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

No, this is not the best way to handle a db connection. You only want the db open and around for as long as necessary and no longer. Usually this means opening the db connection at the place in your code that can know how long to keep it open and then close the connection after using it.

If you are simply referring to the configuration for opening a DB connection, then you could define that configuration object at application start and then pass it as a parameter to your db instantiation code.

import myUserDbCode from '../myUserDbFile';
import myUserMessagesCode from '../myUserMsgsDbFile';

const dbConfig = {
  dbname: 'myFancyDb',
  serverName: 'myDbServerName',
  connectionTimeout: 60
}

(async () => {

  const userList = await myUserDbCode(dbConfig)
    .then((dbResultSet) => {
      return dbResultSet.data;
    }
  };

  const myUser = userList[42];

  const userMessages = await myUserMessagesCode(dbConfig, myUser)
    .then((dbResultSet) => {
      return dbResultSet.data;
    }
  };

  console.log(userMessages);
})();

I recommend following some DB tutorials that show how to build a complete application to see some patterns about how to handle passing configuration options to code and how to manage DB connections.

about 4 years ago · Juan Pablo Isaza 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