English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

NodeJS Basic Tutorial

NodeJS Express.js

NodeJS Buffer&URL;

NodeJS MySql

NodeJS MongoDB

NodeJS File(FS)

NodeJS Others

Node.js MongoError

MongoError: Unable to connect to the server

In this Node.js tutorial, we will learn to fix MongoError: By investigating the scenarios that may trigger this errorUnable to connect to the server.

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

  1. Ensure that the MongoDB service has started and is running.

  2. The URL you provide to the MongoClient's connect() method should be correct.

How to verify if the MongoDB service has started and is running

The start-up of the Mongo Shell should verify this.

If your MongoDB service is not started, you will see the following error in the terminal:

Mongo Shell Terminal

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 [thread1Error: 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 the MongoDB service using the following command:

sudo service mongod start

No errors should be reported when starting the mongod Mongo Daemon.
When the service starts and the MongoDB Shell is started,

Mongo Shell

arjun@w3codebox:~/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 ensure the URL is correct?

When we start the MongoDB Shell, MongoDB will record the URL in the Terminal, similar to the following content:

connecting to: mongodb://127.0.0.1:27017

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

Ensure that you provide the same base URL (the same IP and port) in your Node.js application.

// URL of the running MongoDB service
var url = "mongodb://localhost:27017"; 
 
// MongoDB Client
var MongoClient = require('mongodb').MongoClient; 
 
// Connect 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: Unable to connect to the server sideWe have learned some checkpoints to correct errors.