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

408
Visualizações
How to handle MongoDB Client connection error after it has been cached Mongo shuts down ?

I have created a mongodb native connection and saved it and then using findOne to query a document.

const Promise = require("bluebird");
const MongoClient = require('mongodb').MongoClient;
let mongoDB = undefined;

const getCollection = (collName) => {
    if (mongoDB) {
        return Promise.resolve(mongoDB.collection(collName));
    } else {
        return MongoClient.connect(EXT_CONFS.MONGODB_URL)
            .then(db => {
                mongoDB = db;
                return Promise.resolve(mongoDB.collection(collName));
            }).catch(e => {
               console.error('Error in MongoDb connection');
            });
    }
};

const findOne = (collName, filter, options) => {
    return getCollection(collName)
        .then(collection => {
            return collection.findOne(filter, options);
        })
        .then(doc => {
            return Promise.resolve(doc);
        }).catch(e => {
            console.error(e);
            return Promise.reject(e);
        });
};

Now this all works fine, but if Mongo ShutsDown / Fails after db client is cached, There is no way to handle error. Error never goes to any catch handler :

console.error('Error in MongoDb connection');

or

console.error(e);

I even tried events :

 mongoDB.on('connecting', function () {
     console.log('connecting');
 });
 mongoDB.on('timeout', function (error) {
     console.log('timeout!');
 });
 mongoDB.on('close', function (error) {
     console.log('close!');
 });
 mongoDB.on('error', function (error) {
     console.error('Error in MongoDb connection: ' + error);
 });
 mongoDB.on('connected', function () {
     console.log('connected!');
 });
 mongoDB.on('connection', function () {
     console.log('connected!');
 });
 mongoDB.on('connect', function () {
     console.log('connected!');
 });
 mongoDB.once('open', function () {
     console.log('connection open');
 });
 mongoDB.on('reconnected', function () {
     console.log('reconnected');
 });
 mongoDB.on('disconnected', function () {
     console.log('disconnected');
 });

but no success still. Using NodeJS 4.5.0, MongoDB-Native driver 2.2.24

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You should do something like console.error('Failed to connect to mongodb ',e); you are not outputting the error.

Also some events provide an additional parameter and you are outputting those either. In case of failing to connect to an mongodb server, your application should just notify you it's not the best approach to handle mongodb server start/restart from your application use daemons such as systemd or other process monitoring.

Some events are there to just notify the application that connection was lost or an reconnection is attempted, its up to you to handle what is going to be done when those events are emitted.

You can for example attempt to check mongodb status when an disconnect event is emitted an recreate connection object.

over 4 years ago · Santiago Trujillo Relatório

0

You could wrap the connect statement in a try-catch block.

over 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