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.

Terminal – Starting Mongo Shell

arjun@tutorialkart:~/workspace/nodejs/mongodb$ mongo
MongoDB shell version v3.4.9
connecting to: mongodb://127.0.0.1:27017
2017-10-30T14:32:21.476+0530 W NETWORK  [thread1] Failed to connect to 127.0.0.1:27017, in(checking socket for error after poll), reason: Connection refused
2017-10-30T14:32:21.477+0530 E QUERY    [thread1] Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed :
connect@src/mongo/shell/mongo.js:237:13
@(connect):1:6
exception: connect failed

Start your MongoDB Service with the command below :

sudo service mongod start

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

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

Terminal – Mongo Shell

arjun@tutorialkart:~/workspace/nodejs/mongodb$ mongo
MongoDB shell version v3.4.9
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.9

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 :

connecting to: mongodb://127.0.0.1:27017

mongodb://127.0.0.1:27017 is the base url.

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

node-js-mongodb-connection.js

// URL at which MongoDB service is running
var url = "mongodb://localhost:27017";

// A Client to MongoDB
var MongoClient = require('mongodb').MongoClient;

// Make a connection to MongoDB Service
MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  console.log("Connected to MongoDB!");
  db.close();
});

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.