Best way to handle 'MongoError: failed to connect to server on first connect' in Mongoose

5,015

I am also looking for an answer to your question. So far in my search I believe that calling process.exit is perahps the best method. Because Mongoose lets you start using your models immediately, without waiting for mongoose to establish a connection to MongoDB. That's because mongoose buffers model function calls internally.

As of Mongoose 5.0.10 - Mongoose will not throw any errors by default if you use a model without connecting.

If your connection fails to reconnect, then your app is thinking that it is performing the model operations via the buffer when in fact it will fail.

I've seen developers add an additional Mongodb URI like this:

mongoose.connect(URI1||URI2);

Ultimately, you'll want to ensure your app will always be able to connect to the database rather than perform model functions into the buffer in futility.

There is an option to disable buffering but I'm not sure how that will impact performance.

Share:
5,015

Related videos on Youtube

NG.
Author by

NG.

Software Engineer, hobby programmer and gamer.

Updated on September 18, 2022

Comments

  • NG.
    NG. over 1 year

    In this GitHub issue for mongoose the developer stated that it is intended behaviour to crash the Node.js process if the initial database connection to MongoDB fails. It does this instead of trying to reconnect.

    In my code I catch this error because I want to log it.

    var mongooseOptions = { 
        useMongoClient: true,
        reconnectInterval: 10000,
        reconnectTries: Number.MAX_VALUE 
    };
    
    mongoose.connect(connectionString, mongooseOptions)
        .catch(err => {
            logger.error('Mongodb first connection failed: ' + err.stack);
            // what to do here? - process.exit(0); maybe?
        });
    

    But after that, what is the best practice to do? crash the process? or write my own reconnecting logic? I maybe should mention that the mongodb.service is listed as a requirement for the node.service to start (using systemd in linux).

    [Unit]
    After=mongodb.service
    ...
    

    I am also unsure how often I can expect to see this happen.

    I have also used this guide but I cannot find a clear answer.