Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

214
Visualizações
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}.`);
});
    }
});
about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

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
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda