MongoError: connect ECONNREFUSED 127.0.0.1:27017
06:18 02 Oct 2017

I'm using Node.js with MongoDB using the mongodb package. When I run the mongod command, it works fine and gives "waiting for connection on port 27017". So, mongod seems to be working. But MongoClient does not work and gives an error when I run the node index.js command:

MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]

Enter image description here

I have installed MongoDB 3.4 and my code is:

var MongoClient = require('mongodb').MongoClient;
var dburl       =   "mongodb://localhost:27017/test";
MongoClient.connect(dburl, function(err, db) {
  if (err) {
    throw err;
  }
  console.log('db connected');
  db.close();
});

I have created data/db directories on root and have given write permissions.

The mongod.conf file takes a db path as:

storage: dbPath: /var/lib/mongo

But it seems that it is actually taking the db path as data/db and not var/lib/mongo.

It was working earlier, but it suddenly stopped.

node.js linux mongodb