185

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.

12
  • 3
    Go inside location C:\Program Files\MongoDB\Server\3.4\bin and run mongod.exe and try again Commented Oct 2, 2017 at 10:16
  • 2
    Thanks. But I am on amazon linux server. How to test there?
    – Deepika P.
    Commented Oct 2, 2017 at 10:19
  • 21
    replace localhost with 127.0.0.1 and try. not sure about the result but try and update us. and also try with running below command from terminal ,sudo service mongod start Commented Oct 2, 2017 at 10:24
  • 1
    I already tried this, didn't work. sudo service mongod start gives error- Starting mongod (via systemctl): Job for mongod.service failed because the control process exited with error code. See "systemctl status mongod.service" and "journalctl -xe" for details.
    – Deepika P.
    Commented Oct 2, 2017 at 10:26
  • 3
    I am really surprised how many answer provide a Windows solution (and they are even top rated) despite this question clearly refers to Linux. Commented Apr 11, 2021 at 7:55

47 Answers 47

347

My apps stopped working after upgrading from Node.js 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);
20
  • 5
    MongoDB seems to be not compatible with NodeJS v17. It should be listening on IPv6 "::1" by default and it would work with v17 without any problem.
    – TJJ
    Commented Jan 5, 2022 at 22:16
  • 36
    for me replacing localhost with 127.0.0.1 worked, thanks!
    – Patronics
    Commented Mar 20, 2022 at 23:52
  • 3
    I noticed (with ping localhost) that the localhost of my freshly installed OS points to ::1 (which is ipv6) rather than 127.0.0.1 like it used to previously. That probably means that using mongodb://localhost:27017/ probably will make node try to connect via ipv6, which mongo probably is not listening to.
    – tacone
    Commented Jul 8, 2022 at 8:31
  • 21
    mongodb://0.0.0.0:27017/ worked for me 👍🏻
    – Maxiller
    Commented Jul 9, 2022 at 7:47
  • 15
    0.0.0.0 worked for me too. Never seen something this stupid.
    – M. Kaan
    Commented Jul 22, 2022 at 21:19
244

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

  1. Press the Windows + R keys on your keyboard to open the Run window. Type services.msc and hit Enter on your keyboard or click/tap the OK button. A new window opens up.
  2. 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.

4
  • 9
    For windows 10 path is Control Panel\System and Security\Administrative Tools
    – armin
    Commented Aug 29, 2021 at 18:42
  • If you can't click Start, right click MongoDB, enter Properties and change Startup Type to Manual Commented Dec 14, 2022 at 12:13
  • How do you do this on "macOS Ventura 13.2" ?
    – NOTiFY
    Commented Jan 23, 2023 at 22:53
  • The screenshot clearly shows a Linux environment, not Windows. Commented Dec 3, 2023 at 22:17
29

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

sudo service mongod start
3
  • How can I run this command automatically on restart? Right now I have to run this command each time I restart. Commented Aug 17, 2022 at 16:20
  • not working for me.
    – kvk30
    Commented Nov 8, 2022 at 8:21
  • @Khushalsharma sudo systemctl enable mongod
    – Amos Tanui
    Commented Feb 1, 2023 at 22:44
28

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

1
  • The screenshot clearly shows a Linux environment, not Windows. Commented Dec 3, 2023 at 22:17
22

Instead of this:

const url = "mongodb://localhost:27017";

Use this:

const url = "mongodb://0.0.0.0:27017";
1
  • 1
    This one solve my problem in my case
    – Zed
    Commented Jun 9, 2023 at 14:35
21

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.))

1
  • 2
    @nikhilsugandh - really? The screenshot clearly shows a Linux environment, not Windows. Commented Apr 11, 2021 at 7:53
20

Method 1

If It’s MAC OS, run following command and try again:

brew services restart mongodb-community

Stopping mongodb-community... (might take a while) ==> Successfully stopped mongodb-community (label: homebrew.mxcl.mongodb-community) ==> Successfully started mongodb-community (label: homebrew.mxcl.mongodb-community)

2
  • Error: No available formula with the name "mongodb-community". Did you mean mongodb-atlas-cli?
    – kvk30
    Commented Nov 14, 2022 at 8:42
  • Is there any other method
    – kvk30
    Commented Nov 14, 2022 at 8:42
19

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)

0
14

For Ubuntu users run sudo systemctl restart mongod

1
  • Finally, someone wrote the instruction for Ubuntu, and it worked immediately for my Ubuntu 22.04, thanks a lot. Commented Jan 28, 2023 at 12:49
12

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.

12

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

0
10

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!!

0
9

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.

1
8

You can run Cmd as administrator and write this command to start Mongodb service:

 net start MongoDB

OR

  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 Run MongoDB service

and reopen mongodb

7

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.

1
  • easy solution, it works on my windows 10. thank you Commented May 18, 2022 at 10:14
6

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

Check: Install MongoDB Community Edition on macOS

2
5

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

2
  • If you have it installed and are still having said problem, you forgot to start the services Commented May 21, 2020 at 10:50
  • 4
    "install mongodb" is not an answer for sure...people who post this are users of MongoDB. Commented May 28, 2020 at 20:25
5

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.

0
4

just start the mongo server from terminal

Ubuntu -

     sudo systemctl start mongod
2
  • thx matte. in my case, I was forgetting to run it as sudo.
    – bkupfer
    Commented Aug 4, 2021 at 17:32
  • Solved my problem on Ubuntu 20
    – XpressGeek
    Commented Jan 1, 2022 at 8:44
4

UPDATED ANSWER FOR THIS QUESTION !!

So I tried everything in this forum. but no result!(From my side). so i tried this one:

1)go to control panel

2)Select System and Security and choose last option :Administrative tools.

3)Select Services

4)Search for MongoDB Server (MongoDB)

5)Right click on it and click on run.

6)and close the Services blindly

7)last but not least,change your mongodb url to mongodb://0.0.0.0:27017/

8)Restart your server and that worked for me!.

9)So i tried this by combining 2 answers in this forum !🤣🤣

1
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented Sep 3, 2022 at 8:16
4

I faced the same error then I found that If you are using the latest nodejs (v17.x), then try updating the MongoDB URL from localhost to 127.0.0.1 This worked for me.

3

If you use MongoDb Compass make sure that you have installed MongoDB Community Server.

1
  • 1
    haha, Yes. this is underrated Ans.
    – Coder
    Commented Jan 29, 2023 at 11:19
2

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.

2
  • It is better to comment on your short answers and ideas like other friends Commented Sep 22, 2020 at 4:54
  • This is because the service was disabled. Just open Services > Enable and Start mongod service. You can achieve the same using the command line. Just consult the documentation for exact syntax. Commented Jan 5, 2022 at 23:28
2

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

2

I was getting same error. I was doing everything right like path variables and stating mongodb before running code. Replacing localhost with IP i.e 127.0.0.1 in connection code solved for me.

mongoose.connect('mongodb://127.0.0.1/test', {useNewUrlParser: true, useUnifiedTopology: true});

2

From MongoDB Forums

MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017 Answer

Just change the "URI" from

mongodb://localhost:27017

to

mongodb://127.0.0.1:27017
1
  • or mongodb://0.0.0.0:27017 Commented Feb 18, 2023 at 6:30
2

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}`));

1

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

1

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

2
  • 1
    that has nothing to do with the OPs question. Commented Apr 26, 2020 at 14:39
  • this work for me in windows 10 Commented Sep 16, 2023 at 8:41
1

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.