MongoError: connect ECONNREFUSED 127.0.0.1:27017

node.jsLinuxMongodb

node.js Problem Overview


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.

node.js Solutions


Solution 1 - node.js

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.

Solution 2 - node.js

My apps stopped working after upgrading from Nodejs 14 to 17.

The error I got was

MongoServerSelectionError: connect ECONNREFUSED ::1:27017

The solution was simply replacing localhost by 0.0.0.0. I.e. in my source code I had to change

const uri = "mongodb://localhost:27017/";
const client = new MongoClient(uri);

to

const uri = "mongodb://0.0.0.0:27017/";
const client = new MongoClient(uri);

I am posting this as an answer because I couldn't find the solution anywhere on the Internet and I wasted a lot of time on this one...

Solution 3 - node.js

For windows - just go to Mongodb folder (ex : C:\ProgramFiles\MongoDB\Server\3.4\bin) and open cmd in the folder and type "mongod.exe --dbpath c:\data\db"

if c:\data\db folder doesn't exist then create it by yourself and run above command again.

All should work fine by now.))

Solution 4 - node.js

I've forgot to start MongoDB at all. Go to separate tab in terminal and type:

sudo service mongod start

Solution 5 - node.js

For Windows users.

This happens because the MondgDB server is stopped. to fix this you can,

  1. 1 search for Services ,for that search using the left bottom corner search option.

    2 then there is a gear icon named with 'Services'.

    3 after clicking that you will get a window with lot of services

    4 scroll down and you will find 'MongoDB server (MongoDB)'.

    5 so you will see that there is an option to start the service.

    6 start it.

  2. 1 then open your command prompt.

    2 type mongod

now you can connect to your server.

this steps also working fine if your sql server service down. (find sql server services)

Solution 6 - node.js

Try to start mongoDB server by giving the --dbpath with mongod.

sudo mongod --dbpath /var/lib/mongo/data/db &

'&' in the last will start the mongodb server as service on your server.

Hope it Works.

Solution 7 - node.js

I had below error:

Error: connect ECONNREFUSED 127.0.0.1:27017

In my case, this issue occurred since MongoDB is not installed at all.

The solution was to install MongoDB from below location:
https://www.mongodb.com/download-center/community

After installing the ECONNREFUSED error did not appear again.

Hope that helps.

Solution 8 - node.js

Search services.msc in your device and click start to run the mongoDB server

enter image description here

After started running MongoDB server you will able to run your program

Solution 9 - node.js

For Ubuntu users run sudo systemctl restart mongod

Solution 10 - node.js

I had the same error because i had not installed mongoDB. Make sure that you have mongodb installed and if not, you can download it from here https://www.mongodb.com/download-center/community

Solution 11 - node.js

Press CTRL+ALT+DELETE/task manager , then go to services , find MongoDB , right click on it. start. go back to terminal . npm start it will work.

Solution 12 - node.js

On a mac I had to run brew services start [email protected]

Check: Install MongoDB Community Edition on macOS

Solution 13 - node.js

For Windows users: Mongo version 4.4 Use following commands: NET STOP MONGODB – To stop MongoDB as a service,if this returns "mongoDb service is not running then use below command to start service" NET START MONGODB – To start MongoDB as a service.

This worked for me.

Solution 14 - node.js

just start the mongo server from terminal

Ubuntu -

     sudo systemctl start mongod

Solution 15 - node.js

I just found a solution in the internet , If you are using latest nodejs (v17.x) , then try updating mongodb url from localhost to 127.0.0.1

ref: https://www.mongodb.com/community/forums/t/mongooseserverselectionerror-connect-econnrefused-127-0-0-1-27017/123421/3

Solution 16 - node.js

If you already installed "MongoDB", if you accidentally exit from the MongoDB server, then "restart your system".

This method solved for me...

[On Windows only]

And also another method is there:

press:

Windows + R

type:

services.msc

and click "ok", it opens "services" window, and then search for "MongoDB Server" in the list. After you find "MongoDB Server", right-click and choose "start" from the pop-up menu.

The MongoDb Server will start running.

Hope it works!!

Solution 17 - node.js

I was facing the same issue on windows 10. I just uninstall MongoDB and installed it again and it started working. It solved my problem.

Solution 18 - node.js

most probably your mongo db service is not started. For ubuntu : sudo service mongod start For windows : go to services and start the MongoDB service

also install link for mondoDB service https://www.mongodb.com/download-center/community

I had this problem and i solved it thanks to this man's answer https://stackoverflow.com/a/47433551/7917608

Solution 19 - node.js

I was having the same problem today.. and has been searching for answers.. I am on Ubuntu... however, I could not find the correct one that works on this thread.. after much research the following worked for me finally!! :)

First, after running

mongod dbpath

if appeared that mongodb was looking for the data/db directory.. which was missing in my installed mongodb app.. so I ran the following commands:

$ sudo mkdir -p /data/db

then run,

$ sudo chown -R $USER /data/db

chown - changes ownership of files/dirs. Ie. owner of the file/dir changes to the specified one, but it doesn't modify permissions. As detailed here: https://unix.stackexchange.com/questions/402062/how-are-chown-and-chmod-command-different-in-the-given-operation

Finally, run

`$ sudo systemctl enable mongod.service

It will give a message: Created symlink /etc/systemd/system/multi-user.target.wants/mongod.service → /lib/systemd/system/mongod.service and started the service.

Solution 20 - node.js

I had the same issue on Windows.

Ctrl+C to close mongod, and start mongod again.

Am not sure, but it seems that initially mongod was working opening and closing connections. Then, it was not able to close some earlier connections and reached limit for opened ones. After restarting mongod, it works again.

Solution 21 - node.js

You probably need to continue running your DB process (by running mongod) while running your node server.

Solution 22 - node.js

Please ensure that your mongo DB is set Automatic and running at Control Panel/Administrative Tools/Services like below. That way you wont have to start mongod.exe manually each time.

enter image description here

Solution 23 - node.js

The solution was to install MongoDB from below location: https://www.mongodb.com/download-center/community

Solution 24 - node.js

because you didn't start mongod process before you try starting mongo shell.

Start mongod server

mongod

Open another terminal window

Start mongo shell

mongo

Solution 25 - node.js

In my particular instance, I was connected to a VPN and that was blocking the localhost connection to MongoDB somehow. It worked when I disconnected my VPN. It's a special case, but good to know nonetheless. So anything impeding your network connectivity, Get that fixed.

Solution 26 - node.js

If you are on WSL and trying to access MongoDB from Windows, then you have to install Mongo for WSL.

Solution 27 - node.js

I debugged this same error on my own for over 5 hours. Eventually it worked out for me. Below is a check list of items to make sure they are correct before using Mongoose.

  • MongoDB is installed on your system
  • MongoDB is running as a service before you use 'npm run start'
  • The mongoose code does not have any syntax errors
  • Use promises (.then()) in the connect function for mongoose
  • If you are using 'localhost' in URL, try switching it with '0.0.0.0' or vice versa

Once you have done all this, run the command 'node run start' and hopefully this should work now. To verify, go to mongoDB and see the newly created database.

Below is a sample code for MongoDB and Mongoose that worked for me.

const mongoose = require('mongoose');

const myFunc = () => {
    const userSchema = mongoose.Schema({
        name: String
    });

    const User = mongoose.model("User", userSchema);

    const userObject = new User({
        name: 'Abhishek'
    });

    userObject.save((err, data) => {
        if (err)
            console.log('Error in saving = ' + err);
        if (data)
            console.log('Saved to DB = ' + data)
    }
    );
};

mongoose
    .connect("mongodb://0.0.0.0/userdb")
    .then(myFunc(), err => console.log(`Error = ${err}`));

Solution 28 - node.js

I got this issue with Node.js v17 under Windows.
Found the issue open on mongoose github with some solutions: https://github.com/Automattic/mongoose/issues/10917

I had to either use 127.0.0.1 instead of localhost in the mongoose.connect function, which worked.

Or edit the config file with admin rights notepad. Open admin cmd, go to C:\Program Files\MongoDB\Server\5.0\bin folder, enter command notepad mongod.cfg then edit:

net:
  port: 27017
  ipv6: true

I had to remove bindIp: 127.0.0.1, leaving only port and ipv6, otherwise database wouldn't connect even with ipv6: true. Then restart mongodb service with windows task manager -> services -> mongodb, and using localhost would work.

Apparently using mongod://0.0.0.0:27017/ is not safe: https://stackoverflow.com/questions/17588876/mongodb-conf-bind-ip-127-0-0-1-does-not-work-but-0-0-0-0-works

Solution 29 - node.js

Check where your .sock file is located. For my case, it was in /tmp folder.

Then run the following commands.

chown mongodb:mongodb /tmp/mongodb-27017.sock

sudo systemctl start mongod

mongosh

This worked for me.

For more reference

Solution 30 - node.js

  1. click window key + r key
  2. type services.msc and press ok
  3. wait open service
  4. search mongodb
  5. click right key and start press enter image description here

and reopen mongodb

Solution 31 - node.js

If you are a windows user, right click on Start and open Windows Powershell(Run as administartor). Then type

mongod

That's it. Your database will surely get connected!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDeepika P.View Question on Stackoverflow
Solution 1 - node.jsSonu SouravView Answer on Stackoverflow
Solution 2 - node.jsPage not foundView Answer on Stackoverflow
Solution 3 - node.jsFarid AnsariView Answer on Stackoverflow
Solution 4 - node.jsmatrixb0ssView Answer on Stackoverflow
Solution 5 - node.jsHeshanHHView Answer on Stackoverflow
Solution 6 - node.jsNitin BhanderiView Answer on Stackoverflow
Solution 7 - node.jsManohar Reddy PoreddyView Answer on Stackoverflow
Solution 8 - node.jslahiru dilshanView Answer on Stackoverflow
Solution 9 - node.jsU.AView Answer on Stackoverflow
Solution 10 - node.jsWamala Emmanuel NsubugaView Answer on Stackoverflow
Solution 11 - node.jsDoniyor BoltayevView Answer on Stackoverflow
Solution 12 - node.jsFotios TsakirisView Answer on Stackoverflow
Solution 13 - node.jsNizar KadriView Answer on Stackoverflow
Solution 14 - node.jsSahilView Answer on Stackoverflow
Solution 15 - node.jshariom nagarView Answer on Stackoverflow
Solution 16 - node.jskrnitheesh16View Answer on Stackoverflow
Solution 17 - node.jsyogesh patelView Answer on Stackoverflow
Solution 18 - node.jsFarrukhView Answer on Stackoverflow
Solution 19 - node.jsRichard RosarioView Answer on Stackoverflow
Solution 20 - node.jsNovichokView Answer on Stackoverflow
Solution 21 - node.jsotoloyeView Answer on Stackoverflow
Solution 22 - node.jswise kingView Answer on Stackoverflow
Solution 23 - node.jsAnonymous UnknownView Answer on Stackoverflow
Solution 24 - node.jsMohit RakhadeView Answer on Stackoverflow
Solution 25 - node.jsGokul RamakrishnanView Answer on Stackoverflow
Solution 26 - node.jsGabriel ArghireView Answer on Stackoverflow
Solution 27 - node.jsspiyush0212View Answer on Stackoverflow
Solution 28 - node.jsAli AnwarView Answer on Stackoverflow
Solution 29 - node.jsMohamed AhmedView Answer on Stackoverflow
Solution 30 - node.jsNurulView Answer on Stackoverflow
Solution 31 - node.jsArunesh NahaView Answer on Stackoverflow