80

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);
Kamil Naja
  • 6,267
  • 6
  • 33
  • 47
Karam Haj
  • 1,080
  • 2
  • 9
  • 20
  • 3
    You might have installed MongoDB but it certainly is not running. You really should check those installation instructions and ensure you can connect from the mongo shell before doing anything else. And just to be clear we are on the same page `npm install mongodb` is not what we are talking about here. We are talking about actually "installing the server" for your platform. – Neil Lunn May 04 '18 at 10:57
  • 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 . – lliance Nov 12 '20 at 17:18

33 Answers33

61

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.

Vishnu
  • 11,614
  • 6
  • 51
  • 90
55

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
NadZ
  • 1,024
  • 9
  • 10
  • 7
    THIS SAVED MY LIFE... been trying to figure this out for days now. that ```?authSource=admin``` is what did it for me!!!!! – Ren44 Jul 07 '19 at 01:13
  • 1
    [This](https://stackoverflow.com/questions/40608669/what-does-authsource-means-in-mongo-database-url) is the meaning of `authSource` –  Oct 16 '20 at 16:38
17

I faced the same issue and I have done some research about it and found that this problem is solved by running the command on your terminal.

sudo service mongod start

then run mongo on terminal

Jagroop
  • 1,777
  • 1
  • 6
  • 20
12

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);
});
Cory
  • 121
  • 5
12

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')
Community
  • 1
  • 1
KeitelDOG
  • 4,750
  • 4
  • 18
  • 33
9

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

Steve
  • 4,372
  • 26
  • 37
4

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.

Pritt Balagopal
  • 1,476
  • 2
  • 18
  • 32
  • 3
    If you've whitelisted your IP address under Security > Network Access > IP Whitelist and then try to connect from a different IP address, Mongo will block the connection. It's a security feature to ensure only trusted IPs can connect to the database. You just need to go to the aforementioned section of the Mongo DB Atlas site and either add your current IP address (permanent or temporary) to the whitelist or temporarily allow access from anywhere (i.e. 0.0.0.0/0 for all IP addresses). It is not recommended that you permanently allow access from anywhere for obvious security reasons. – mepley Jul 09 '19 at 21:44
  • When you connect to `localhost` (or `127.0.0.1`) as given in the question, then you don't need any internet connection at all. – Wernfried Domscheit Feb 14 '23 at 15:02
4

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

Aleem
  • 549
  • 6
  • 13
3

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.

GangaRam Dewasi
  • 631
  • 7
  • 11
3

I solved this problem by upgrading major version of mongoose:

Before doing this, make sure (using mongo shell) that you have the correct URL and a running mongo server is available at that URL and the problem still persists.

   "dependencies": {
-    "mongoose": "^5.4.13",
+    "mongoose": "^6.2.4",
   }
oklas
  • 7,935
  • 2
  • 26
  • 42
  • How is this answer related to the question? – Wernfried Domscheit Feb 14 '23 at 15:03
  • Why exactly it may not be relevant to this question? It solves the problem. You might be wondering how exactly it solves the problem? It is unlikely that anyone sees the point in wasting time on a detailed research of the cause. – oklas Feb 14 '23 at 15:15
  • Your answer has nothing to do with the error message in the question. The MongoDB server was not installed or not started which is totally different to your solution. – Wernfried Domscheit Feb 14 '23 at 15:21
  • The same error can be caused by different reasons. You mentioned cases when the mongo server is not running or not installed. We also can add incorrectly specified url and other cases. For all of them, there is probably already exists an answer. If not, you can add it if you wish. This does not except the causing a mismatched version of a dependency to cause the same error. And this answer let you know about it. The relation to the error may not seem obvious, which only makes the answer even more useful. – oklas Feb 14 '23 at 16:54
  • Again, the error message which is given in the question, is not solved by your answer. Your answer is rather confusing for other people who get the same error. – Wernfried Domscheit Feb 14 '23 at 18:28
  • I had this problem after updating os and brew. I solved the problem in this way. When I was looking for an answer, I found this question. I added the answer because it helped me and will help others. You expressed your opinion in the comments too. I hope the topic is covered. – oklas Feb 15 '23 at 07:38
  • I've added a note following that people shouldn't get confused. In such cases, the error would be more understandable if it was something like the protocol is incompatible or has a different version. rsync also gives unexplained errors in cases where the protocol is incompatible. – oklas Feb 15 '23 at 08:56
2

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.

Udit Jain
  • 137
  • 1
  • 2
2

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
isofttechn
  • 400
  • 1
  • 6
  • 19
2

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.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Labham Jain
  • 308
  • 3
  • 8
  • 1
    why do you write every word uppercase on first letter? This is quite exhausting to read. – Logemann Apr 28 '20 at 13:32
  • Oh! :-( But I'm Comfortable With Uppercase – Labham Jain Apr 29 '20 at 16:32
  • 1
    https://stackoverflow.com/help/how-to-ask --> "Spelling, grammar and punctuation are important! Remember, this is the first part of your question others will see - you want to make a good impression. If you're not comfortable writing in English, ask a friend to proof-read it for you." – Logemann Apr 29 '20 at 19:57
2

this was my erros:

Connecting to: mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.6.2 MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017

SOLUTION:

The best Answes is if you using mac M1 and M2

use restrat with sudo like below

MongoNetworkError solution

sudo brew services restart mongodb-community@6.0
Jagtar Singh
  • 171
  • 4
1

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

1

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.

1

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.

Mahdieh Shavandi
  • 4,906
  • 32
  • 41
1

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.
jaideep
  • 1,631
  • 17
  • 19
1

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
Hussein
  • 95
  • 1
  • 1
  • 5
1

For me the problem resolved when I started the MongoDB on port other than 27017. Even though nothing was running on 27017 but the problem resolved when I started it on another port.

To do that navigate to the /etc/mongod.conf and change the port: 27017 to some other port like port: 27019.

Then restart the service by:
sudo systemctl restart mongod.service.

And then try to connect to MongoDB by specifying the --port parameter like:
mongod --port 27019, or
mongo --port 27019

Best!

Dhruv Awasthi
  • 149
  • 1
  • 4
  • `mongod` is the MongoDB **server** whereas `mongo` is a **client**. These two commands do fundamentally different things. Most likely you (try to) started several instances of mongod. – Wernfried Domscheit Feb 14 '23 at 15:11
0

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:

obayral
  • 141
  • 3
  • 15
0
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.

astroboy
  • 177
  • 1
  • 13
0

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

Fenrera
  • 1
  • 1
0

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.

rohit anand
  • 162
  • 1
  • 6
0

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.

Showrin Barua
  • 1,737
  • 1
  • 11
  • 22
Hacke
  • 209
  • 2
  • 10
0

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.

BoyePanthera
  • 546
  • 5
  • 10
0

In my case the problem was that there was another instance of mongoDB server running I had shutdown my computer without stopping the server hence when I tried running mongosh it gives me that error. Try restarting the computer it will shutdown all the servers and the erro was gone.

0

I was trying to connect, without starting the service. This is how i fixed the error (MacOS env).

$ brew services start mongodb-community@6.0
$ mongosh // connected to db and fixed the error.
$ brew services stop mongodb-community@6.0
Mohammed Shahed
  • 840
  • 2
  • 15
-1

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

Hasan Sefa Ozalp
  • 6,353
  • 5
  • 34
  • 45
-1

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

-1

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
Don Le
  • 9
  • 4
-1

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)

Pankaj
  • 169
  • 2
  • 11
-2

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