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

222
Vistas
Async: Connecting to MongoDB after the server started

I would love to know a few things about Node.js async and MongoDB. If the server starts before my connection to, and my templates or Ajax depend on data from the database will serving (I precompile my handlebars) the HTML file fail or will my templates/Ajax wait for the connection and then continue?

If it works, I would love to understand better how exactly it worked! If it fails, how can I "fix" it elegantly?

This is an example of a solution, using hoisting (seems bad to me tbh):

//connect to db
mongodb.connect("someDBplace",
    (err, db)=>{
    if(err){
        return generalLogger.error(`The database has failed to connect: ${err}.`);
    }else{ //start the server now:
        generalLogger.info(`Connected to database: ${stringify(db.databaseName)}.`);

server.listen(`${port}`, (err)=>{
    if(err){
        generalLogger.error(err);
    }
    //for demo: console th eMIMEtype
    generalLogger.info(`The Server started on port: ${port}.`);
});
    }
});
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Yes, this is a correct way to do it. If you want to make sure that the database is available before the server starts serving requests, then you need to start the server in the callback of the database connection method.

Some higher level frameworks like Hapi may provide you some mechanisms to simplify the case when you need to wait for several things before starting. For example see the Hapi plugins:

  • https://hapijs.com/tutorials/plugins
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