MongoError: connect ECONNREFUSED 127.0.0.1:27017

SyntaxFix
1 min readDec 7, 2022

--

I’m using NodeJS wih MongoDB using mongodb package. When I run 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 error when I run 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 install mongo db 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 given write permissions. mongod.conf file takes db path as-

storage: dbPath: /var/lib/mongo

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

It working earlier but suddenly stopped.

Solution is

This happened probably because the MongoDB service isn’t started. Follow the below steps to start it:

  1. Go to Control Panel and click on Administrative Tools.
  2. Double click on Services. A new window opens up.
  3. Search MongoDB.exe. Right click on it and select Start.

The server will start. Now execute npm start again and the code might work this time.

More answers are at syntaxfix.com

--

--

SyntaxFix

Curated Solutions On Popular Questions — On All Programming Languages, Cloud Computing, Tools etc