166

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.

Wernfried Domscheit
  • 54,457
  • 9
  • 76
  • 110
Deepika P.
  • 1,699
  • 2
  • 10
  • 12
  • 3
    Go inside location C:\Program Files\MongoDB\Server\3.4\bin and run mongod.exe and try again – chetan mekha Oct 02 '17 at 10:16
  • 2
    Thanks. But I am on amazon linux server. How to test there? – Deepika P. Oct 02 '17 at 10:19
  • 17
    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 – chetan mekha Oct 02 '17 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. Oct 02 '17 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. – Wernfried Domscheit Apr 11 '21 at 07:55
  • This happened to me when I forgot to start the docker instance I was using with mongo. – Charlotte_Anne Jun 30 '21 at 18:37
  • 1
    Try manually stopping the server and starting again. I also faced the same problem on my Mac M1. Although mongodb was running but the mongoose could not connect to it. – Harshit Gangwar Nov 14 '21 at 10:01
  • On Mac I replaced localhost with 127.0.0.1 , it works. – Theodory Aug 24 '22 at 06:53
  • @HarshitGangwar, Any help? I am also facing the same issue. – kvk30 Nov 14 '22 at 08:46
  • To future users: Please do not take this question as a precedent for usage of images. Images should not be used when the image is of text that could be written in the post. [See here](https://meta.stackoverflow.com/a/285557/11107541) for why. – starball Dec 27 '22 at 03:18
  • Does this answer your question? [Can't connect to MongoDB 6.0 Server locally using Nodejs driver](https://stackoverflow.com/questions/74609210/cant-connect-to-mongodb-6-0-server-locally-using-nodejs-driver) – Wernfried Domscheit May 13 '23 at 08:34

45 Answers45

279

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);
Page not found
  • 2,454
  • 2
  • 10
  • 19
  • 4
    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 Jan 05 '22 at 22:16
  • What makes `mongodb://0.0.0.0:27017/` ?, try to connect to every ip? – elVengador Feb 08 '22 at 23:43
  • 28
    for me replacing localhost with 127.0.0.1 worked, thanks! – Patronics Mar 20 '22 at 23:52
  • Thanks a lot, brother. Can you please tell me why this error occurred? why localhost is not working – Md. Maruf Sarker Mar 21 '22 at 13:45
  • 2
    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 Jul 08 '22 at 08:31
  • 18
    mongodb://0.0.0.0:27017/ worked for me – Maxiller Jul 09 '22 at 07:47
  • 13
    0.0.0.0 worked for me too. Never seen something this stupid. – M. Kaan Jul 22 '22 at 21:19
  • @pagenotfound thank you so much! I surfed the web for hours and you saved my head and my time! Thank and Thank you and Thank you!!! – Motsi Aug 09 '22 at 17:33
  • Thank you so much, bro. I was banging my head for a week. All the tutorials show the same localhost:27017 mongodb://127.0.0.1:27017/db_name works for me – Tarun Aug 21 '22 at 14:23
  • Thank you so much, I have been searching for this for three days. I also had another issue before which was not being able to connect to the MongoDB even. and just wasting my time on their website Mac issue not finding the data/db mongod --dbpath=/Users/youUserName/data/db – Hesham El Masry Sep 09 '22 at 21:25
  • It happened to me too, after I upgraded from `node 16` to `node 18`. I used `127.0.0.1` and it worked. I don't know why that happened in the first place though! Thank you anyway – Amir Oct 26 '22 at 22:08
  • In addition, 127.0.0.1 also works, Thanks – Khan Sharukh Nov 09 '22 at 07:48
  • This worked for me on WIndows 10 – Renie Dec 04 '22 at 06:22
  • I spent hours resolving this issue and changing `localhost` to `0.0.0.0` worked for me. Thanks a lot, brother!! – Prashil Shah Jan 13 '23 at 08:32
  • I simply lost 4 hours of searching and finally changing from `localhost` to `0.0.0.0` worked at my end – Reza Heidari Jan 17 '23 at 10:23
  • Wow. Surprised with this fix. +1 – Kirataka Jan 22 '23 at 11:45
  • very helpful. but need to know more informations about the error – Md Shayon Mar 17 '23 at 06:01
  • I don't think `0.0.0.0` is the perfect solution, because IP `0.0.0.0` should/cannot be used as destination address (see [0.0.0.0](https://en.wikipedia.org/wiki/0.0.0.0)). Better use IP `127.0.0.1` or the real hostname or bind the IPv6 Address, see [Can't connect to MongoDB 6.0 Server locally using Nodejs driver](https://stackoverflow.com/questions/74609210/cant-connect-to-mongodb-6-0-server-locally-using-nodejs-driver/74610881#74610881) It also explains why `localhost` does not work – Wernfried Domscheit May 13 '23 at 08:58
210

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.

Sonu Sourav
  • 2,926
  • 2
  • 12
  • 25
26

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

sudo service mongod start
matrixb0ss
  • 785
  • 8
  • 10
23

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

lahiru dilshan
  • 690
  • 9
  • 13
19

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

Farid Ansari
  • 813
  • 5
  • 7
17

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)

HeshanHH
  • 653
  • 7
  • 9
16

Instead of this:

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

Use this:

const url = "mongodb://0.0.0.0:27017";
samayo
  • 16,163
  • 12
  • 91
  • 106
Sehrish Waheed
  • 1,230
  • 14
  • 17
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.

Manohar Reddy Poreddy
  • 25,399
  • 9
  • 157
  • 140
12

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)

Bayram Binbir
  • 1,531
  • 11
  • 11
11

For Ubuntu users run sudo systemctl restart mongod

U.A
  • 2,991
  • 3
  • 24
  • 36
  • Finally, someone wrote the instruction for Ubuntu, and it worked immediately for my Ubuntu 22.04, thanks a lot. – Ahmad Bader Jan 28 '23 at 12:49
11

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

hariom nagar
  • 370
  • 3
  • 5
10

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.

Nitin Bhanderi
  • 334
  • 2
  • 9
8

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

krnitheesh16
  • 152
  • 1
  • 6
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.

7

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

Eng_Farghly
  • 1,987
  • 1
  • 23
  • 34
Nurul
  • 89
  • 1
  • 1
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

5

On a mac I had to run brew services start mongodb-community@4.4

Check: Install MongoDB Community Edition on macOS

Fotios Tsakiris
  • 1,310
  • 1
  • 18
  • 24
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.

Nizar Kadri
  • 321
  • 2
  • 10
4

just start the mongo server from terminal

Ubuntu -

     sudo systemctl start mongod
Sahil
  • 59
  • 8
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 !

  • 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](/help/how-to-answer). – Community Sep 03 '22 at 08:16
3

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

akbar
  • 625
  • 6
  • 12
3

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.

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

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

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

O_K
  • 922
  • 9
  • 14
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

Farrukh
  • 153
  • 1
  • 8
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.

1

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

Gabriel Arghire
  • 1,992
  • 1
  • 21
  • 34
1

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: mongodb.conf bind_ip = 127.0.0.1 does not work but 0.0.0.0 works

Ali Anwar
  • 91
  • 1
  • 3
1

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

1

i faced this problem when i updated my Node js from version 16.18.0 to 18.12.0

No need to change your URI you have to just go to your windows service and find mongo db, once it will appear, just stop the service and start again thats it

1

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
0

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

otoloye
  • 677
  • 7
  • 11
0

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

wise king
  • 39
  • 1
  • 7
0

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
Mohit Rakhade
  • 351
  • 4
  • 8
0

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.

0

First, you need to start mongod service and then make connection. To do so, open your terminal (powershell in Windows) and write command mongod enter image description here

Now connect using MongoDB compass it will work

0

Add family: 4 as a option.
family - Whether to connect using IPv4 or IPv6. This option is passed to Node.js' dns.lookup() function. If you don't specify this option, the MongoDB driver will try IPv6 first and then IPv4 if IPv6 fails. If your mongoose. connect(uri) call takes a long time, try mongoose.connect(uri, { family: 4 })

export const connectWithDb =()=>{
    mongoose.connect(uri,{ useNewUrlParser: true, useUnifiedTopology: true,family: 4}).then(db => console.log('DB is connected'))
    .catch(err => console.log(err));
}
Nirob Hasan
  • 413
  • 4
  • 3
0

If you use mac and you want to start mongodb compass you need to start mongo service.

if you haven't mongo service

  1. brew tap mongodb/brew
  2. brew install mongodb-community
  3. brew services start mongodb-community

OR brew services restart mongodb-community

0

I was facing the same ERROR.

connect ECONNREFUSED ::1:27017 Connection Failed!

Because I have updated my node version. I rollback to the last version of node.js then it worked for me.

0

Add follwing code in app.js:

const { MongoClient } = require('mongodb')

// Create Instance of MongoClient for mongodb
const client = new MongoClient('mongodb://127.0.0.1:27017')

// Connect to database
client.connect()
    .then(() => {
        console.log('Connected Successfully!')
        
        //Close the database connection
        console.log('Exiting..')
        client.close()
    })
    .catch(error => console.log('Failed to connect!', error))

Source: Connect MongoDB with Node JS

Kamran Riyaz
  • 79
  • 2
  • 3
0

After I install the MongoDB Community Server my problem was solved. ✔️

Taib Islam Dipu
  • 437
  • 4
  • 10
0

At first, you must be installed the MongoDB Community version from here : https://www.mongodb.com/download-center/community/releases

then Start the MongoDB Service

-1

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.

Novichok
  • 42
  • 3
-1

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!

  • 3
    He already has said that he is not a windows user and is on an Amazon linux instance. – Hoppo Jun 06 '20 at 14:53