[node.js] ECONNREFUSED error when connecting to mongodb from node.js

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)

This question is related to node.js mongodb

The answer is


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


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

I use some public wifi and switch to my phone connection


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


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.


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>";

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.


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


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?


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


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.


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


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.


Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to mongodb

Server Discovery And Monitoring engine is deprecated Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017] Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified Failed to start mongod.service: Unit mongod.service not found db.collection is not a function when using MongoClient v3.0 MongoError: connect ECONNREFUSED 127.0.0.1:27017 MongoDB: How To Delete All Records Of A Collection in MongoDB Shell? How to resolve Nodejs: Error: ENOENT: no such file or directory How to create a DB for MongoDB container on start up?