[Error: failed to connect to [localhost:27017]] from NodeJS to mongodb - node.js

I am having problem connecting to MongoDB from NodeJS using following sample code. I tried running "mongod" with or without sudo but nodejs code still fail to connect. I am able to successfully connect to database using "mongo".
Running on : MAC OS 10.6.8
var mongoClient = require('mongodb').MongoClient;
mongoClient.connect("mongodb://localhost:27017/test", function(error, db) {
if(!error){
console.log("We are connected");
}
else
console.dir(error);
});
get following error running above code : [Error: failed to connect to [localhost:27017]]
Also tried mongoose but similar error:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
console.log("DB connected");
// yay!
});
Output: connection error: [Error: failed to connect to [localhost:27017]]
Here is the log of mongod
mongod --help for help and startup options
2014-07-11T23:33:47.843-0700 kern.sched unavailable
2014-07-11T23:33:47.849-0700 [initandlisten] MongoDB starting : pid=29942 port=27017 dbpath=/data/db 64-bit host=usc8bcc8a0d0b1
2014-07-11T23:33:47.849-0700 [initandlisten]
2014-07-11T23:33:47.849-0700 [initandlisten] ** WARNING: soft rlimits too low. Number of files is 256, should be at least 1000
2014-07-11T23:33:47.849-0700 [initandlisten] db version v2.6.3
2014-07-11T23:33:47.849-0700 [initandlisten] git version: nogitversion
2014-07-11T23:33:47.849-0700 [initandlisten] build info: Darwin usc8bcc8a0d0b1 10.8.0 Darwin Kernel Version 10.8.0: Tue Jun 7 16:33:36 PDT 2011; root:xnu-1504.15.3~1/RELEASE_I386 i386 BOOST_LIB_VERSION=1_49
2014-07-11T23:33:47.849-0700 [initandlisten] allocator: system
2014-07-11T23:33:47.849-0700 [initandlisten] options: {}
2014-07-11T23:33:47.850-0700 [initandlisten] journal dir=/data/db/journal
2014-07-11T23:33:47.850-0700 [initandlisten] recover : no journal files present, no recovery needed
2014-07-11T23:33:47.901-0700 [initandlisten] waiting for connections on port 27017
2014-07-11T23:34:47.901-0700 [clientcursormon] mem (MB) res:48 virt:2810
2014-07-11T23:34:47.901-0700 [clientcursormon] mapped (incl journal view):320
2014-07-11T23:34:47.901-0700 [clientcursormon] connections:0

Never mind, I was able to resolve the issue by using 127.0.0.1 instead of localhost, not sure why I have to use ip address. My tomcat, apache, redis, and even node server all works using localhost but not the mongodb. Is there is config I need change to make it work using local host?

Try adding 127.0.0.1 localhost in /private/etc/hosts file.

This issue can occur if your mongoDBwasnot shutdown properly
Mongodb can't connect to localhost but can connect to localhost's IP address
Start your mongoDB Server using follwoingcommand and then try same ./mongod --bind_ip localhost

yes , I came across this error too, and my hosts is as follow:
127.0.0.1 xxxxxx(the ip of my computer)
and when I ran npm start in express project, it got an error like that . After I tried to change the mapping of 127.0.0.1 to localhost, it had no error.

The first time, I made the obvious mistake that mongod (the mongo Server) was not even running.
The second time, I had both the Server (mongod) and the Client (mongo) running on my Windows; in separate Command Prompts (of course mongo running first). mongod and/or its Command Prompt was "hung up" (i.e. the last line only said this, and the last line remained like this despite attempts to connections:)
2017-06-20T12:31:02.937-0600 I NETWORK [thread1] waiting for connections on port 27017
I clicked in the Command Prompt pressed the space-bar to "kick it" , and the Command Prompt printed lines like these:
2017-06-20T12:31:48.517-0600 I NETWORK [thread1] connection accepted from 127.0.0.1:50260 #1 (1 connection now open)
Which worked!

Somebody on Github found a solution:
Instead of writing:
Mongoose.connect(config.database.url);
Write:
Mongoose.connect(config.database.url, {
keepAlive: true,
reconnectTries: Number.MAX_VALUE,
useMongoClient: true
});
(Source https://github.com/Automattic/mongoose/issues/5399)

Related

Cant connect to docker mongodb

I am have not used both docker and node a lot so I hope its a simple mistake. I am using docker compose. If I through a browser access,
http://localhost:27017/ I get an:
It looks like you are trying to access MongoDB over HTTP on the native
driver port.
Also logs suggest my mongodb is healty. Last line from when I tried to access through my browser I guess.
2017-01-25T21:11:13.509+0000 I JOURNAL [initandlisten] journal
dir=/data/db/journal 2017-01-25T21:11:13.509+0000 I JOURNAL
[initandlisten] recover : no journal files present, no recovery needed
2017-01-25T21:11:13.546+0000 I JOURNAL [durability] Durability thread
started 2017-01-25T21:11:13.547+0000 I JOURNAL [journal writer]
Journal writer thread started 2017-01-25T21:11:13.568+0000 I CONTROL
[initandlisten] MongoDB starting : pid=1 port=27017 dbpath=/data/db
64-bit host=150c248f4cc7 2017-01-25T21:11:13.568+0000 I CONTROL
[initandlisten] db version v3.0.2 2017-01-25T21:11:13.568+0000 I
CONTROL [initandlisten] git version:
6201872043ecbbc0a4cc169b5482dcf385fc464f 2017-01-25T21:11:13.569+0000
I CONTROL [initandlisten] OpenSSL version: OpenSSL 1.0.1e 11 Feb 2013
2017-01-25T21:11:13.569+0000 I CONTROL [initandlisten] build info:
Linux ip-10-171-120-232 3.2.0-4-amd64 #1 SMP Debian 3.2.46-1 x86_64
BOOST_LIB_VERSION=1_49 2017-01-25T21:11:13.569+0000 I CONTROL
[initandlisten] allocator: tcmalloc 2017-01-25T21:11:13.569+0000 I
CONTROL [initandlisten] options: {} 2017-01-25T21:11:13.573+0000 I
NETWORK [initandlisten] waiting for connections on port 27017
2017-01-25T21:11:17.843+0000 I NETWORK [initandlisten] connection
accepted from 172.20.0.1:44148 #1 (1 connection now open)
2017-01-25T21:11:17.843+0000 I NETWORK [initandlisten] connection
accepted from 172.20.0.1:44146 #2 (2 connections now open)
2017-01-25T21:11:17.853+0000 I NETWORK [conn2] end connection
172.20.0.1:44146 (1 connection now open) 2017-01-25T21:11:17.998+0000 I NETWORK [conn1] end connection 172.20.0.1:44148 (0 connections now
open)
So it looks that my mongodb is up running. When I in in my node application try to access it I get.
{ MongoError: failed to connect to server [localhost:27017] on first
connect
at Pool. (/usr/src/app/node_modules/mongodb-core/lib/topologies/server.js:326:35)
at emitOne (events.js:96:13)
at Pool.emit (events.js:188:7)
at Connection. (/usr/src/app/node_modules/mongodb-core/lib/connection/pool.js:270:12)
at Object.onceWrapper (events.js:290:19)
at emitTwo (events.js:106:13)
at Connection.emit (events.js:191:7)
at Socket. (/usr/src/app/node_modules/mongodb-core/lib/connection/connection.js:175:49)
at Object.onceWrapper (events.js:290:19)
at emitOne (events.js:96:13) name: 'MongoError', message: 'failed to connect to server [localhost:27017] on first connect' }
My code trying to access the mongodb
const express = require('express');
const gh = require('./src/fetch');
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017/myApp';
// Constants
const PORT = 8888;
// App
const app = express();
app.get('/', function (req, res) {
MongoClient.connect(url, function (err, db) {
if (err) {
console.log(err);
} else {
console.log("Connected correctly to server");
db.close();
}
});
res.send('Hello world\n');
});
app.listen(PORT);
console.log('Running on http://localhost:' + PORT);
My docker-compose looks like this.
version: '2'
services:
web:
image: gh-api
ports:
- "8888:8888"
environment:
- KEY=abc
restart: always
links:
- mongoDB
depends_on:
- mongoDB
mongoDB:
image: mongo:3.0.2
ports:
- "27017:27017"
Dockerfile for gh-api
FROM node:7.4-onbuild
EXPOSE 8888
Could you change url to your mongodb from:
const url = 'mongodb://localhost:27017/myApp';
to
const url = 'mongodb://mongoDB/myApp';
I had similar issue with my demo blog application and with that change application started working.
Edit
The best explanation that I could found is explanation of docker-compose links.
Containers for the linked service will be reachable at a hostname
identical to the alias, or the service name if no alias was specified.
So in order to access mongoDB container from web container you should use mongoDB as host name in web container.
It looks like you are trying to access MongoDB over HTTP on the native driver port.
That port is to be used by the mongo driver. If you really want/need to access the rest interface you have to use port 28017 and start mongo with the --rest flag. An example:
$ docker run --rm -p 28017:28017 mongo mongod --rest
To access a container from another, with docker compose use the service name, as pointed out by Ivan.
In my case everything was correctly setup just like answered in this question however I got this error caused by "boot race", basically my Node app would boot before mongo image and therefore it would try to connect to mongo before it's up and running. So I changed my connection code to retry again with something like this:
init().then((mongo) => main({ mongo })).catch(e => init())
function init(){
return MongoClient.connect(mongoConnectionURL)
}
function main({ mongo }){
const server = express()
server.listen(port, host);
}
I tought, this was supposed to be solved using depends_on property inside compose file, but as far as I understand, depends_on only makes sure to start other services, doesn't make sure they were initialized in proper order.

connect remotely to mongoDB server

I have installed MongoDB on a fresh Centos7 server.
I have installed MongoDB accroding to this tutrial: https://www.liquidweb.com/kb/how-to-install-mongodb-on-centos-7/
The installation was completed succsessfully, when I write mongo on the shell this is the output:
[root#centos-512mb-nyc3-01 ~]# mongo
MongoDB shell version: 2.6.12
connecting to: test
Server has startup warnings:
2016-12-31T18:37:11.734+0000 [initandlisten]
2016-12-31T18:37:11.734+0000 [initandlisten] ** WARNING: Readahead for /var/lib/mongo is set to 4096KB
2016-12-31T18:37:11.734+0000 [initandlisten] ** We suggest setting it to 256KB (512 sectors) or less
2016-12-31T18:37:11.734+0000 [initandlisten] ** http://dochub.mongodb.org/core/readahead.
I want to connect remotly to mongo via RoboMongo or NodeJS app.
but when I have tried mongo mongodb://138.197.80.108/
I get network unreachable.
There is something that I need to do to connect remotly to mongo?
Thanks :)
BTW - I havn't set any password\user
I have bind machine's IP address according to: https://www.mkyong.com/mongodb/mongodb-allow-remote-access/
and added port 27017 to the fire wall tables.

nodejs application - mongodb connection fails with error "ECONNREFUSED"

Background Information
I'm playing around with my first nodejs test app that is attempting to connect to a remote mongodb.
Problem:
The connection is failing with the following message:
admin#testdev:~/Documents/nodejs_tests$ sudo nodejs index.js
Server has started.
Request for / received
About to route a request for: /
inside db connect method
Request for /favicon.ico received
About to route a request for: /favicon.ico
inside db connect method
MongoError: connect ECONNREFUSED
null
MongoError: connect ECONNREFUSED
null
Here's the logic to connect:
function connect_nimble() {
console.log("inside db connect method");
MongoClient.connect("mongodb://10.1.1.1:27017/test", function(err,db) {
console.log(err);
console.log(db);
if(!err) {
console.log("booya! Connected to mongo");
return true;
}
});
}
What I've checked so far:
I've made sure that the database server is using port 27017. Here's what I see in the mongodb logs when i restart the database:
admin#mongotest:~$ tail -f /var/log/mongodb/mongod.log
2015-07-21T09:52:41.452-0500 I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'.
2015-07-21T09:52:41.452-0500 I CONTROL [initandlisten] ** We suggest setting it to 'never'
2015-07-21T09:52:41.452-0500 I CONTROL [initandlisten]
2015-07-21T09:52:41.452-0500 I CONTROL [initandlisten] db version v3.0.4
2015-07-21T09:52:41.452-0500 I CONTROL [initandlisten] git version: 0481c958daeb2969800511e7475dc66986fa9ed5
2015-07-21T09:52:41.452-0500 I CONTROL [initandlisten] OpenSSL version: OpenSSL 1.0.1f 6 Jan 2014
2015-07-21T09:52:41.452-0500 I CONTROL [initandlisten] build info: Linux ip-10-45-73-23 3.13.0-24-generic #46-Ubuntu SMP Thu Apr 10 19:11:08 UTC 2014 x86_64 BOOST_LIB_VERSION=1_49
2015-07-21T09:52:41.452-0500 I CONTROL [initandlisten] allocator: tcmalloc
2015-07-21T09:52:41.452-0500 I CONTROL [initandlisten] options: { config: "/etc/mongod.conf", net: { bindIp: "127.0.0.1" }, storage: { dbPath: "/var/lib/mongodb" }, systemLog: { destination: "file", logAppend: true, path: "/var/log/mongodb/mongod.log" } }
**2015-07-21T09:52:41.470-0500 I NETWORK [initandlisten] waiting for connections on port 27017**
I've made sure I have a database called "test" by starting "mongo"... and then switching in and out of the test database using the "use test" / "use admin" commands.
I don't believe I have authorization turned on. This is what I have in the mongo.conf file:
# Turn on/off security. Off is currently the default
#noauth = true
#auth = true
And to prove it, in order to get into the test database on the server via command line, I just have to type "mongo" and then by default, I'm in the test database. So I think I can safely assume I don't have any authentication going on.
Just in case, I also checked netstat for the port number:
admin#mongotest:~$ sudo netstat -taupen | grep mongo
tcp 0 0 127.0.0.1:27017 0.0.0.0:* LISTEN 117 6465150 18792mongod
admin#mongotest:~$
I'm currently reading the manual to see if there's anything else I should be checking. I'm also reading through the various stackoverflow posts that are similar, but I haven't found me an answer yet.
Any suggestions?
I can see in your logs that Mongo is listening on 127.0.0.1. This is likely your problem. You will have to change the bind-ip address configuration setting to allow Mongo to listen to specific or all IP addresses. You can find how to do this here: Cannot connect to mongodb using machine ip
Open a terminal.
Type mongod & and check the stacktrace.
This is an example of a failing start
I STORAGE [initandlisten] exception in initAndListen: 29 Data directory /data/db not found., terminating
I NETWORK [initandlisten] shutdown: going to close listening sockets...
I NETWORK [initandlisten] shutdown: going to flush diaglog...
I CONTROL [initandlisten] now exiting
To fix this, Create the folder /data/db
In the terminal, type mkdir /data/db
Type againmongod
It works !!
[initandlisten] ** WARNING: Access control is not enabled for the database.
I CONTROL [initandlisten] ** Read and write access to data and configuration is unrestricted.
I CONTROL [initandlisten]
I CONTROL [initandlisten]
I CONTROL [initandlisten] ** WARNING: soft rlimits too low. Number of files is 256, should be at least 1000

MEAN.js Could not connect to MongoDB

in creating my app with MEAN.js can not do mongodb connect on port 27017 in any way.
I installed mongodb manually in directory
~$ ls -la /etc/init.d/mongod
output
lrwxrwxrwx 1 root root 56 Nov 4 20:45 /etc/init.d/mongod -> /home/myuser/projects/packages/linux-mongodb/bin/mongod
I try to run the file or `` server.js` grunt` the NASC repository command and got the following error:
Running node server.js i receive this output:
Application loaded using the "development" environment configuration
Failed to load c ++ bson extension, using pure JS version
Insecurely using http protocol
MEAN.JS application started on port 27017
Could not connect to MongoDB!
Error: connection closed
Repository URL:
https://github.com/meanjs/mean
Some hint of what might be?
I look forward personal contact.
Thanks in advance!
Link for reference:
https://stackoverflow.com/a/22557417/3332734
running cat /etc/mongod.conf
# mongod.conf
# Where to store the data.
# Note: if you run mongodb as a non-root user (recommended) you may
# need to create and set permissions for this directory manually,
# e.g., if the parent directory isn't mutable by the mongodb user.
dbpath=/var/lib/mongodb
###dbpath=/home/myuser/projects/packages/mongodb-linux/databases
#where to log
logpath=/var/log/mongodb/mongod.log
###logpath=/home/myuser/projects/packages/mongodb-linux/mongod.log
logappend=true
port = 27017
# Listen to local interface only. Comment out to listen on all interfaces.
bind_ip = 127.0.0.1
# Disables write-ahead journaling
# nojournal = true
# Enables periodic logging of CPU utilization and I/O wait
#cpu = true
# Turn on/off security. Off is currently the default
#noauth = true
#auth = true
# Verbose logging output.
#verbose = true
# Inspect all client data for validity on receipt (useful for
# developing drivers)
#objcheck = true
# Enable db quota management
#quota = true
# Set oplogging level where n is
# 0=off (default)
# 1=W
# 2=R
# 3=both
# 7=W+some reads
#diaglog = 0
# Ignore query hints
#nohints = true
# Enable the HTTP interface (Defaults to port 28017).
#httpinterface = true
httpinterface = true
# Turns off server-side scripting. This will result in greatly limited
# functionality
#noscripting = true
# Turns off table scans. Any query that would do a table scan fails.
#notablescan = true
# Disable data file preallocation.
#noprealloc = true
# Specify .ns file size for new databases.
# nssize = <size>
# Replication Options
# in replicated mongo databases, specify the replica set name here
#replSet=setname
# maximum size in megabytes for replication operation log
#oplogSize=1024
# path to a key file storing authentication info for connections
# between replica set members
#keyFile=/path/to/keyfile
Run mongo in console and retrieve output:
$ mongo
MongoDB shell version: 2.6.5
connecting to: test
2014-11-05T19:23:18.957-0200 warning: Failed to connect to 127.0.0.1:27017, reason: errno:111 Connection refused
2014-11-05T19:23:18.958-0200 Error: couldn't connect to server 127.0.0.1:27017 (127.0.0.1), connection attempt failed at src/mongo/shell/mongo.js:146
exception: connect failed
Run mongod in console and retrieve output:
$ mongod
mongod --help for help and startup options
2014-11-05T19:26:53.215-0200 [initandlisten] MongoDB starting : pid=3487 port=27017 dbpath=/data/db 64-bit host=francis-tosystems
2014-11-05T19:26:53.215-0200 [initandlisten] db version v2.6.5
2014-11-05T19:26:53.215-0200 [initandlisten] git version: e99d4fcb4279c0279796f237aa92fe3b64560bf6
2014-11-05T19:26:53.215-0200 [initandlisten] build info: Linux build8.nj1.10gen.cc 2.6.32-431.3.1.el6.x86_64 #1 SMP Fri Jan 3 21:39:27 UTC 2014 x86_64 BOOST_LIB_VERSION=1_49
2014-11-05T19:26:53.215-0200 [initandlisten] allocator: tcmalloc
2014-11-05T19:26:53.215-0200 [initandlisten] options: {}
2014-11-05T19:26:53.215-0200 [initandlisten] exception in initAndListen: 10296
*********************************************************************
ERROR: dbpath (/data/db) does not exist.
Create this directory or give existing directory in --dbpath.
See http://dochub.mongodb.org/core/startingandstoppingmongo
*********************************************************************
, terminating
2014-11-05T19:26:53.215-0200 [initandlisten] dbexit:
2014-11-05T19:26:53.215-0200 [initandlisten] shutdown: going to close listening sockets...
2014-11-05T19:26:53.215-0200 [initandlisten] shutdown: going to flush diaglog...
2014-11-05T19:26:53.215-0200 [initandlisten] shutdown: going to close sockets...
2014-11-05T19:26:53.215-0200 [initandlisten] shutdown: waiting for fs preallocator...
2014-11-05T19:26:53.215-0200 [initandlisten] shutdown: lock for final commit...
2014-11-05T19:26:53.215-0200 [initandlisten] shutdown: final commit...
2014-11-05T19:26:53.215-0200 [initandlisten] shutdown: closing all files...
2014-11-05T19:26:53.216-0200 [initandlisten] closeAllFiles() finished
2014-11-05T19:26:53.216-0200 [initandlisten] dbexit: really exiting now
Or run mongod
$ mongod --config /etc/mongod.conf &
[1] 3568 2014-11-05T19:28:16.867-0200 SEVERE: Failed global initialization: FileNotOpen Failed to open "/var/log/mongodb/mongod.log"
EDIT
I am no longer using MEAN.js, but I continue my studies with MongoDB and node.js
The problem was that I did not know how to start mongodb to connect to the database
This year I learned a lot about mongodb and node.js and I understood what I needed to do.
With your help I have three steps:
Open a console with mongod --dbpath /project/path-do-database/
I connected my API to mongodb, passing the right port
Open a second console by starting the node.js API with node ornodemon and passing the project's main javascript file.
Basically, you need to have 2 terminals running at the same folder.
One for mongoDB, one for your application.
On the first terminal,
1>> npm install -g meanjs
1>> yo meanjs
then fill up your application name, author name, etc.
1>> npm install
Open up a 2nd terminal to start the mongodb server
2>> mongod
Go back to the first terminal and run it
1>> npm start
You are starting your meanjs app on the same port as your mongodb server (27017). If you do not specify a port for meanjs, it will start on 3000 in a development environment.
I know it is probably late, but error logs says it all:
ERROR: dbpath (/data/db) does not exist.
I belive you need to create /data/db folders or it was created somewhere else.
It is already answered here:
mongodb Mongod complains that there is no /data/db folder

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)
ECONNREFUSED error
There are few reasons of this error in node :
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)
Your server is not running e.g. in this case please check your mongoose server is running or run by using following command.
$ mongod
There is also possibility your localhost is not configured properly so use 127.0.0.1:27017 instead of localhost.
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.
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')
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?
very strange, but in my case, i switch wifi connection...
I use some public wifi and switch to my phone connection
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 same problem. It was resolved by running same code in Administrator Console.
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.
sometimes you need to check the rightfulness of the IP, firewall, port forwarding, etc, if your target database is in other machines.
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...
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 manually started the mongodb service.
Control Panel -> Administrative tools -> Services -> Mongodb
Then either start/restart it. It's done!
Happy Coding! :-)
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
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
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
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 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
you can go to mongoDB compass client and follow these steps:
1.Click Fill in connection fields individually:
2.In hostname type : 127.0.0.1
3. Click CONNECT.
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
For my case this resolved:
Control Panel -> Administrative tools -> Services -> Start MongoDB Server
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

Resources