MongoError: failed to connect to server

In this Node.js Tutorial, we shall learn to fix MongoError: failed to connect to server by investigating into the scenarios that could trigger this error.

To fix Node.js MongoError: failed to connect to server, follow the two checkpoints

  1. Make sure MongoDB Service is up and running.
  2. The URL you provide to the MongoClient.connect() method should be correct.

How to Verify if MongoDB Service is up and running

Starting the Mongo Shell should verify this.

If your MongoDB Service is not up, you would get an Error in the Terminal as below :

Start your MongoDB Service with the command below :

There should be no error reported when you start Mongo Daemon, mongod.

And when the Service is up, and Mongo Shell is started,

How to make sure that the URL is correct?

When we start Mongo Shell, MongoDB logs the URL to Terminal, similar to something like below :

mongodb:// is the base url.

Make sure that you are providing the same base URL (same IP and Port) in your Node.js Application.

Conclusion :

In this Node.js MongoDB Tutorial – Node.js MongoError: failed to connect to server, we have learned some of the checkpoints to fix the error.