MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]

node.jsMongodbExpress

node.js Problem Overview


I'm new in nodeJS, started learning by following a trailer on youtube, everything goes well until I added the connect function if mongodb,

mongo.connect("mongodb://localhost:27017/mydb")

when I run my code on cmd (node start-app), get the following error,

MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]

Could someone explain me which step I missed ? my code :

var express = require("express");
var MongoClient = require('mongodb');
var url = "mongodb://localhost:27017/mydb";
var webService = require("./webService");
var server = express();

MongoClient.connect(url, function (err, db) {
    if (err) throw err;
    console.log("Database created!");
    db.close();
});

server.use(express.urlencoded({ extended: true }));

server.set('views', __dirname);

server.get('/', function (request, response) {
    response.sendFile(__dirname + '/MainPage.html');
});

server.get('/Sign', function (request, response) {
    response.render(__dirname + '/Sign.ejs');
});

server.post("/signUp", webService.signUp);

server.post("/createUser", webService.createUser);

server.listen(5500);

node.js Solutions


Solution 1 - node.js

You have to install MongoDB database server first in your system and start it.

Use the below link to install MongoDB

https://docs.mongodb.com/manual/installation/

If you have installed MongoDB check if the server is in which state (start/stop). Try to connect through mongo shell client.

Solution 2 - node.js

Many of them don't add this, especially in AWS EC2 Instance, I had the same issue and tried different solutions. Solution: one of my database URL inside the code was missing this parameter 'authSource', adding this worked for me.

mongodb://myUserName:MyPassword@ElasticIP:27017/databaseName?authSource=admin

Solution 3 - node.js

After trying EVERY solution google came up with on stack overflow, I found what my particular problem was. I had edited my hosts file a long time ago to allow me to access my localhost from my virtualbox.

Removing this entry solved it for me, along with the correct installation of mongoDB from the link given in the above solution, and including the correct promise handling code:

mongoose.connect('mongodb://localhost/testdb').then(() => {
console.log("Connected to Database");
}).catch((err) => {
    console.log("Not Connected to Database ERROR! ", err);
});

Solution 4 - node.js

I faced same issue but after a lot of RND. I found that whts the problem so run this command on your terminal.

sudo service mongod start

then run mongo on terminal

Solution 5 - node.js

You're IP address probably changed.

If you've recently restarted your modem, this changes your IP which was probably whitelisted on Atlas.

Soooo, you'll need to jump back onto Atlas and add your new IP address to the whitelist under Security>Network Access.

Solution 6 - node.js

Following the logic behind @CoryM's answer above :

>After trying EVERY solution google came up with on stack overflow, I found what my particular problem was. I had edited my hosts file a long time ago to allow me to access my localhost from my virtualbox. > >Removing this entry solved it for me...

I had edited my hosts file too for Python Machine Learning setup 2 months ago. So instead of removing it because I still need it, I use 127.0.0.1 in place of localhost and it worked :

mongoose.connect('mongodb://127.0.0.1/testdb')

Solution 7 - node.js

This had occurred to me and I have found out that it was because of faulty internet connection. If I use the public wifi at my place, which blocks various websites for security reasons, Mongo refuses to connect. But if I were to use my own mobile data, I can connect to the database.

Solution 8 - node.js

If the mongoDB server is already installed and if you are unable to connect from a remote host then follow the below steps,

Login to your machine, open mongodb configuration file located at /etc/mongod.conf and change the bindIp field to specific ip / 0.0.0.0 , after that restart mongodb server.

    sudo vi /etc/mongod.conf
  • The file should contain the following kind of content:

      systemLog:
          destination: file
          path: "/var/log/mongodb/mongod.log"
          logAppend: true
      storage:
          journal:
              enabled: true
      processManagement:
          fork: true
      net:
          bindIp: 127.0.0.1  // change here to 0.0.0.0
          port: 27017
      setParameter:
          enableLocalhostAuthBypass: false
    
  • Once you change the bindIp, then you have to restart the mongodb, using the following command

      sudo service mongod restart
    
  • Now you'll be able to connect to the mongodb server, from remote server.

Solution 9 - node.js

I solved this problem by upgrading major version of mongoose:

   "dependencies": {
-    "mongoose": "^5.4.13",
+    "mongoose": "^6.2.4",
   }

Solution 10 - node.js

just run mongod in terminal on the base folder if everything has been set up like installing mongo db and the client for it like mongoose. After running the command run the project file that you are working on and then the error shouldn't appear.

Solution 11 - node.js

You can check detail of error by running this command

sudo service mongod status

if error is something like this

  • Failed to unlink socket file /tmp/mongodb-27017.sock Unknown error
  • Fatal Assertion 40486 at src/mongo/transport/transport_layer_asio.cpp 670

simply running this will resolve your issue

rm /tmp/mongodb-27017.sock

Solution 12 - node.js

I had this issue while working at the local Starbucks and I remembered that when I initially set up my database through Mongo Atlas. I set my IP address to be able to access the database. After looking through several threads, I changed my IP address on Atlas and the issue went away. Hope this helps someone.

Solution 13 - node.js

I don't know if this might be helpful, but when I did this it worked:

Command mongo in terminal.

Then I copied the URL which mongo command returns, something like

mongodb://127.0.0.1:*port*

I replaced the URL with this in my JS code.

Solution 14 - node.js

first create folder by command line mkdir C:\data\db (This is for database) then run command mongod --port 27018 by one command prompt(administration mode)- you can give name port number as your wish

Solution 15 - node.js

My problem was the wrong port number for mongoDB server.

I had:

DATABASE_URL= "mongodb://localhost:3000/node-express-mongodb-server"

in my .env file (my environmental variables), but I had written it before running mongoDB server. So when I ran the mongoDB server, it wrote a different port number and I had to change it. I changed it to the right port number (which was written on my cmd window by mongoDB):

DATABASE_URL= "mongodb://localhost:27017/node-express-mongodb-server"

and now it works fine.

Solution 16 - node.js

So when none of the above solutions worked for me, after installing everything correctly, I thought to restart the system.

It's working now.

Note that I did everything said above, but no luck. The only restart worked for me.!! You may also want to restart once.

Solution 17 - node.js

if you are a Mac user just upgrade your homeBrew from terminal:

$ brew upgrade
$ mongod --config usr/local/etc/mongod.config
$ Xcode-select --install
$ mongo

Solution 18 - node.js

  1. If you haven't installed mongodb, install it.

  2. open a new terminal, type "mongo". This is going to connect you to a MongoDB instance running on your localhost with default port 27017:

Solution 19 - node.js

My case was a little different. After restarting my system, I had not whitelisted my IP address on Mongo while doing local development.

Select Network Access > Add IP Address > Add your current IP Address

Solution 20 - node.js

mongoose.connect('mongodb://localhost:27017/').then(() => {
console.log("Connected to Database");
}).catch((err) => {
console.log("Not Connected to Database ERROR! ", err);
});

Better just connect to the localhost Mongoose Database only and create your own collections. Don't forget to mention the port number. (Default: 27017)

For the best view, download Mongoose-compass for MongoDB UI.

Solution 21 - node.js

This one helped me. Try creating a new folder, if your MongoDB is installed in C:\Program Files the folder should be called db and in a folder data. C:\data\db

When you start the mongod there should be a log where the db 'isnt found'.

Solution 22 - node.js

I connected to a VPN and the connection accomplished. I was using school's WiFi which has some restrictions apparently.

Solution 23 - node.js

This worked for me.

mongoose.Promise = global.Promise;
  .connect(
    "mongodb://127.0.0.1:27017/mydb",
    { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true}).then(db => {
      console.log("Database connected");
    }).catch(error => console.log("Could not connect to mongo db " + error));

I was using localhost, so i changed it to:

mongodb://127.0.0.1:27017/mydb

Solution 24 - node.js

I guess you must be connecting to cloud.mongodb.com to your cluster.

One quick fix is to go to the connection tab and add your current IP address(in the cluster portal of browser or desktop app). The IP address must have changed due to a variety of reasons, such as changing the wifi.

Just try this approach, it worked for me when I got this error.

Solution 25 - node.js

Your firewall blocked port 27017 which used to connect to MongoDB.

Try to find which firewall is being used in your system, e.g. in my case is csf, config file placed at

/etc/csf/csf.conf

find TCP_IN & TCP_OUT as follow and add port 27017 to allowed incoming and outgoing ports

# Allow incoming TCP ports
TCP_IN = "20,21,22,25,53,80,110,143,443,465,587,993,995,2222,27017"

# Allow outgoing TCP ports
TCP_OUT = "20,21,22,25,53,80,110,113,443,587,993,995,2222,27017"

Save config file and restart csf to apply it:

csf -r

Solution 26 - node.js

this might help someone if you installed your mongo on .msi setup kindly open the software and select repair instead of install and try again, that works for me .

Solution 27 - node.js

You have to install MongoDB database server first in your system and start it.

Use the below link to install MongoDB

If you have already installed MongoDB database in your system then you have to check that your DB is in start position or not with the help of following steps:

  1. press CTRL + Shift + Esc
  2. go to the service tab and search for Mongo
  3. check the status - it may be stopped. So click on the Services tab at the bottom right corner and again search for MongoDB
  4. Click on it and start the DB by right click or in left panel.

Solution 28 - node.js

Your node version has been upgraded. So please follow below step

  1. install nvm
  2. and install old version of node eg. nvm i 16.12.0
  3. nvm use 16.12.0

usefull command of nvm

nvm list available (will show available version of node)

Solution 29 - node.js

If the error happens on macbook run this command to keep the mongodb server running.

mongod --config /usr/local/etc/mongod.conf --fork

The issue majorly is that your mongodb server is rejecting the connection it might be that the server is not on/active eventhough it has been installed on your macbook.

Solution 30 - node.js

If Install before Mongodb Just Start with this code :

brew services start mongodb-community
next => mongod

> If Not Install before this Way

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

Solution 31 - node.js

You need to initialize your mongoDB database first, you can run "mongod" in your terminal and then it will be working fine.

Solution 32 - node.js

just install MongoDB on your system. That's it.

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
Questionكرم حاج يحيىView Question on Stackoverflow
Solution 1 - node.jsVishnuView Answer on Stackoverflow
Solution 2 - node.jsNadZView Answer on Stackoverflow
Solution 3 - node.jsCoryView Answer on Stackoverflow
Solution 4 - node.jsnagender pratap chauhanView Answer on Stackoverflow
Solution 5 - node.jsSteveView Answer on Stackoverflow
Solution 6 - node.jsKeitelDOGView Answer on Stackoverflow
Solution 7 - node.jsPritt BalagopalView Answer on Stackoverflow
Solution 8 - node.jsGangaRam DewasiView Answer on Stackoverflow
Solution 9 - node.jsoklasView Answer on Stackoverflow
Solution 10 - node.jsUdit JainView Answer on Stackoverflow
Solution 11 - node.jsAleemView Answer on Stackoverflow
Solution 12 - node.jsPedro NunezView Answer on Stackoverflow
Solution 13 - node.jsLabham JainView Answer on Stackoverflow
Solution 14 - node.jsMrutyunjaya KarView Answer on Stackoverflow
Solution 15 - node.jsMahdieh ShavandiView Answer on Stackoverflow
Solution 16 - node.jsHackeView Answer on Stackoverflow
Solution 17 - node.jsHusseinView Answer on Stackoverflow
Solution 18 - node.jsobayralView Answer on Stackoverflow
Solution 19 - node.jsjaroraView Answer on Stackoverflow
Solution 20 - node.jsastroboyView Answer on Stackoverflow
Solution 21 - node.jsFenreraView Answer on Stackoverflow
Solution 22 - node.jsHasan Sefa OzalpView Answer on Stackoverflow
Solution 23 - node.jsisoftTechView Answer on Stackoverflow
Solution 24 - node.jsrohit anandView Answer on Stackoverflow
Solution 25 - node.jsDon LeView Answer on Stackoverflow
Solution 26 - node.jsllianceView Answer on Stackoverflow
Solution 27 - node.jsjaideepView Answer on Stackoverflow
Solution 28 - node.jsPankajView Answer on Stackoverflow
Solution 29 - node.jsBoyePantheraView Answer on Stackoverflow
Solution 30 - node.jsuser11313461View Answer on Stackoverflow
Solution 31 - node.jsOmar Vasquez HernandezView Answer on Stackoverflow
Solution 32 - node.jsKhushwant kodechaView Answer on Stackoverflow