70

I know I'm doing some very stupid and noobish, but I'm hoping someone can help me set up a basic database connection to mongodb from node.js on a mac.

I've installed mongodb using homebrew, seems to have worked quite well. I have started the server (mongod) as the locally logged in user, and opened a second terminal and confirmed that I can connect to it by using mongo. When I run mongo I get the message "connecting to: localhost:27017/test" followed by a command prompt. Ran a few commands in the mongo shell everything seems to be working there. Left both terminals open and running.

I've also confirmed that I can reach the web interface at localhost:28017.

I installed node.js and added the mongoose package. Now attempting to connect using a super simple node.js app (also running as locally logged in user):

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');

I receive the following error

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: connect ECONNREFUSED
    at errnoException (net.js:901:11)
    at Object.afterConnect [as oncomplete] (net.js:892:19)

Banging my head against the wall trying to get something so simple to work. What am I missing?

Edit: Here are the logs from mongod. As you can see I tried multiple times and they're all failing rather instantaneously:

Thu Dec  5 08:19:43.700 [initandlisten] MongoDB starting : pid=14412 port=27017 dbpath=/usr/local/var/mongodb 64-bit host=mobadmins-MacBook-Pro-3.local
           08:19:43.700 [initandlisten] db version v2.4.8
           08:19:43.700 [initandlisten] git version: nogitversion
           08:19:43.700 [initandlisten] build info: Darwin mobadmins-MacBook-Pro-3.local 12.4.0 Darwin Kernel Version 12.4.0: Wed May  1 17:57:12 PDT 2013; root:xnu-2050.24.15~1/RELEASE_X86_64 x86_64 BOOST_LIB_VERSION=1_49
           08:19:43.700 [initandlisten] allocator: tcmalloc
           08:19:43.700 [initandlisten] options: { bind_ip: "127.0.0.1", config: "/usr/local/etc/mongod.conf", dbpath: "/usr/local/var/mongodb", logappend: "true", logpath: "/usr/local/var/log/mongodb/mongo.log", rest: true }
           08:19:43.700 [initandlisten] journal dir=/usr/local/var/mongodb/journal
           08:19:43.700 [initandlisten] recover : no journal files present, no recovery needed
           08:19:43.729 [websvr] admin web console waiting for connections on port 28017
           08:19:43.729 [initandlisten] waiting for connections on port 27017
           08:22:34.561 [initandlisten] connection accepted from 127.0.0.1:52160 #3 (1 connection now open)
           08:22:34.563 [conn3] recv(): message len 1124073472 is too large. Max is 48000000
           08:22:34.563 [conn3] end connection 127.0.0.1:52160 (0 connections now open)
           08:24:41.298 [initandlisten] connection accepted from 127.0.0.1:52166 #4 (1 connection now open)
           08:24:41.304 [conn4] end connection 127.0.0.1:52166 (0 connections now open)
           08:25:06.938 [initandlisten] connection accepted from 127.0.0.1:52168 #5 (1 connection now open)
           08:25:06.943 [conn5] end connection 127.0.0.1:52168 (0 connections now open)
           08:25:18.220 [initandlisten] connection accepted from 127.0.0.1:52172 #6 (1 connection now open)
           08:25:18.225 [conn6] end connection 127.0.0.1:52172 (0 connections now open)
           08:25:38.811 [initandlisten] connection accepted from 127.0.0.1:52175 #7 (1 connection now open)
           08:25:38.816 [conn7] end connection 127.0.0.1:52175 (0 connections now open)
agoldencom
  • 1,196
  • 1
  • 8
  • 13
  • 4
    Try passing the default port in the connection URL: "mongodb://localhost:27017/test" – Hector Correa Dec 04 '13 at 21:43
  • 1
    It maybe a port conflict issue.If we try running a node server with second time with a same port the same error will come – shanmugharaj Dec 05 '13 at 03:31
  • 1
    Good ideas both. However I've tried disconnecting any existing connections to the mongodb and adding the port to no avail. – agoldencom Dec 05 '13 at 13:26
  • 1
    Given that mongod is running and I can connect to it using mongo, this smells of some type of failure in my instance of node.js. Perhaps a reinstall could help? – agoldencom Dec 05 '13 at 14:41

21 Answers21

59

ECONNREFUSED error

There are few reasons of this error in node :

  1. Your port is already serving some service so it will refuse your connection.

    go to command line and get pid by using following command

    $ lsof -i:port_number

    Now kill pid by using

    $ kill -9 pid(which you will get by above command)

  2. Your server is not running e.g. in this case please check your mongoose server is running or run by using following command.

    $ mongod

  3. There is also possibility your localhost is not configured properly so use 127.0.0.1:27017 instead of localhost.

Anshul
  • 9,312
  • 11
  • 57
  • 74
21

OK, this was another case of not being truly forthcoming in the info I posted above. My node.js app was very simple, but I was including another couple lines in my node.js code that apparently caused this issue.

Specifically, I had another variable declared which was calling some other code that made a separate database call using incorrect db info. This is why, when using Xinzz's code, the console log error seemed not to change. It wasn't actually the mongoose.connect command that was throwing the error!

Lesson learned, localize the problem and comment out unrelated code! Sorry guys, I knew this was me being dumb.

agoldencom
  • 1,196
  • 1
  • 8
  • 13
19

For me I had to change 'localhost' to '127.0.0.1' and then it started working again:

mongoose.connect('mongodb://127.0.0.1/test')
Jonathan
  • 1,007
  • 16
  • 12
8

Use this code to setup your mongodb connection:

var mongoose = require('mongoose');

var mongoURI = "mongodb://localhost:27017/test";
var MongoDB = mongoose.connect(mongoURI).connection;
MongoDB.on('error', function(err) { console.log(err.message); });
MongoDB.once('open', function() {
  console.log("mongodb connection open");
});

Make sure mongod is running while you start the server. Are you using Express or just a simple node.js server? What is the error message you get with the above code?

Xinzz
  • 2,242
  • 1
  • 13
  • 26
  • 2
    Unfortunately I receive the exact same error using the code above. Mongod is definitely running as I can view the mongod web page at http://localhost:28017/. I am a noob so I'm not entirely sure, but I went through an installation process for node.js and I'm running the server by typing 'node app.js' in a terminal, so I believe that I'm running a simple node.js server. – agoldencom Dec 05 '13 at 14:06
  • 4
    ECONNREFUSED usually means that either mongo is not running or your application cannot access the port it's running on. You can access http://localhost:27017/? – Xinzz Dec 05 '13 at 14:45
  • 2
    I can access localhost:27017 by using mongo from terminal. I can access localhost:28017 from a web browser. mongod is definitely running, and on that port! – agoldencom Dec 05 '13 at 14:52
6

You can just use your local IP address (e.g. 127.0.0.1), instead of using localhost.

(localhost = 127.0.0.1:27017)

'mongodb://127.0.0.1:27017/<ele.Name>'

This is how i got my solution

Aditi Singh
  • 61
  • 1
  • 4
  • 1
    Thank you! this worked for me. I suspect its because not everyone's local host points to 127.0.0.1:27017 by default, which can lead to problems in a node.js or python app. – Roshan May 12 '23 at 05:51
3

very strange, but in my case, i switch wifi connection...

I use some public wifi and switch to my phone connection

itzhar
  • 12,743
  • 6
  • 56
  • 63
  • 2
    This was also problem for me, despite it sounding strange ... i guess the local wifi had blocked some port-s, so switiching to my phone connection solved that – Pero122 May 09 '19 at 09:28
3

I had facing the same issue while writing a simple rest api using node.js eventually found out it was due to wifi blockage and security reason . try once connecting it using your mobile hotspot . if this be the reason it will get resolved immediately.

  • I was stuck with this for more than 5 hours and tried a lot of things, Thanks for the answer it worked immediately with hotspot. The firewall is blocking the connection. – Rahul Sonone Jan 22 '19 at 10:30
3

mongod was running fine locally on my system. I could connect to it with Mongo Compass, but mongoose simply refused to connect. The magic word is directConnection=true, as in

mongodb://127.0.0.1:27017/test?directConnection=true

Versions:

  • mongoose 6.5.2
  • mongodb 4.4.13 Community
  • node 18.5.0
pmont
  • 2,083
  • 22
  • 43
2

I had same problem. It was resolved by running same code in Administrator Console.

Sheikh Abdul Wahid
  • 2,623
  • 2
  • 25
  • 24
1

I had the same issue. What I did is to run mongodb command in another terminal. Then, run my application in another tab. This resolved my problem. Though, I am trying other solution such as creating a script to run mongodb before connection is made.

Ezrqn Kemboi
  • 897
  • 1
  • 12
  • 19
  • Did you find any other solution to this error? Just experiencing the same error when testing my REST API in Postman and I have tried figuring it out but no solution yet. – Dev Enock Nov 01 '22 at 14:02
1

sometimes you need to check the rightfulness of the IP, firewall, port forwarding, etc, if your target database is in other machines.

goodhyun
  • 4,814
  • 3
  • 33
  • 25
1

I had the same issue, all I did was add a setTimeout of about 10 seconds before trying to connect to the Mongo server and it solved the issue right up. I dont know why I had to add a delay but it worked...

max
  • 11
  • 1
1

I also got stucked with same problem so I fixed it like this :

If you are running mongo and nodejs in docker container or in docker compose

so replace localhost with mongo (which is container name in docker in my case) something like this below in your nodejs mongo connection file.

var mongoURI = "mongodb://mongo:27017/<nodejs_container_name>";
Dashrath Mundkar
  • 7,956
  • 2
  • 28
  • 42
1

I manually started the mongodb service.

Control Panel -> Administrative tools -> Services -> Mongodb

Then either start/restart it. It's done!

Happy Coding! :-)

Abhinit
  • 21
  • 1
1

If you're trying to connect to a remote MongoDB server and getting the ECONNREFUSED error, make sure the bind ip option is set up to 0.0.0.0.

See https://www.mongodb.com/docs/manual/core/security-mongodb-configuration/ for more information or use the MongoDB config file (mongod.conf, read more) like this:

net:
  bindIp: 0.0.0.0
Jan Švábík
  • 314
  • 2
  • 13
  • 1
    This is what worked for me. But first I had to systemctl stop mongod, then I used vim (I'm not a vim user, I just know i (for insert), esc (to get out of editing mode), :wq (to save file)). Now I can connect! – Stephen J Feb 18 '23 at 09:32
0

Check this post. https://stackoverflow.com/a/57589615

It probably means that mongodb is not running. You will have to enable it through the command line or on windows run services.msc and enable mongodb.

Nicholas Mberev
  • 1,563
  • 1
  • 14
  • 14
0

I tried every possible solution,butit didn't help me. I took a break and I changed the following. Simple typo. May help someone is same situation. From: app.listen((port)=>console.log(Server is running at port ${PORT}))

To: app.listen(PORT, console.log(Server is running at port ${PORT})) The earlier got me to connect to database mongo atlas but get request was Error: connect ECONNREFUSED

bijayadhs
  • 81
  • 3
0

you can go to mongoDB compass client and follow these steps: 1.Click Fill in connection fields individually: enter image description here

2.In hostname type : 127.0.0.1 enter image description here

3. Click CONNECT.

Hakim Asa
  • 443
  • 3
  • 15
0

Mongodb was not running but I had the module for node.js The database path was missing. Fix was create new folder in the root so run sudo mkdir -p /data/db/ then run sudo chown id -u /data/db

0

For my case this resolved:

Control Panel -> Administrative tools -> Services -> Start MongoDB Server

-1

Hello this is fun and I mean it's fun. Headover to start button and typeservice from there ho Down to and look for mongodb.right click it and click start. Mongod will start. Go back to your project and thank me later

Capiyo
  • 1
  • 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](/help/how-to-answer). – Community Aug 08 '22 at 11:54