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

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

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 Denunciar

0

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

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