Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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); 
like image 263
كرم حاج يحيى Avatar asked May 04 '18 10:05

كرم حاج يحيى


People also ask

How do I access MongoDB on localhost?

To connect to your local MongoDB, you set Hostname to localhost and Port to 27017 . These values are the default for all local MongoDB connections (unless you changed them). Press connect, and you should see the databases in your local MongoDB.

How does MongoDB connect to node js database?

To create a database in MongoDB, start by creating a MongoClient object, then specify a connection URL with the correct ip address and the name of the database you want to create. MongoDB will create the database if it does not exist, and make a connection to it.


1 Answers

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 
like image 175
NadZ Avatar answered Sep 18 '22 11:09

NadZ