ECONNREFUSED error when connecting to mongodb from node.js - 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

Related

I can't connect to mongo db in ubuntu

MongoDB shell version v3.6.3
connecting to: mongodb://127.0.0.1:27017
2018-10-01T17:38:22.425+0000 W NETWORK [thread1] Failed to connect to 127.0.0.1:27017, in(checking socket for error after poll), reason: Connection refused
2018-10-01T17:38:22.426+0000 E QUERY [thread1] Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed :
connect#src/mongo/shell/mongo.js:251:13
#(connect):1:6
exception: connect failed
I get an error when I try to run mongo on the terminal.
I tried to reinstall and removed lock file and restarted it, but It still doesn't work. I am using AWS, is it some problem about inbound, outbound of network setting in AWS, Or any other problem?
Like the comments above, if you are trying to connect to a mongodb instance on the same host, using 127.0.0.1 it is a mongodb configuration problem, so, that is not possible to be any AWS Security Rules.
So, considering it is a mongodb problem, first try to repair it inside the host with:
sudo rm /var/lib/mongodb/mongod.lock
sudo mongod --repair
sudo service mongodb restart
sudo service mongod status
Refer: https://stackoverflow.com/a/29083477/8407784
After resolved the mongodb config problem, you need to test your connection from another host, setting /etc/mongod.conf - bind_ip = 0.0.0.0 (that means all interfaces), only for testing
Then you need to set your AWS Security Rules on the host instance allowing the external instance to access it on port 27017.

mongodb connect fail in osx

I'm newer to mongode, I use shell to start mongodb service but failed and get following error. What should I do?
mongod log
enter image description here
mongo log
MongoDB shell version v3.4.4
connecting to: mongodb://127.0.0.1:27017
2017-05-07T07:59:40.141+1000 W NETWORK [thread1] Failed to connect to 127.0.0.1:27017, in(checking socket for error after poll), reason: Connection refused
2017-05-07T07:59:40.142+1000 E QUERY [thread1] Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed :
connect#src/mongo/shell/mongo.js:237:13
#(connect):1:6
exception: connect failed
Try this. Open terminal, and at the prompt type:
sudo chown -R `id -un` /data/db
Exactly as written. This will give you write access to the /data/db directory which is what Mongo is complaining about. It should prompt you for your password. Once it does enter it and hit enter. After that, kill mongod, if running, and restart.
Make sure the MongoDB server (mongod) is listening on the right interface.
Listening on 127.0.0.1 (loopback interface) will only work locally. If you want to handle remote requests you will have to listen on a network interface that can be accessed remotely. Listening on 0.0.0.0 will listen on all network interfaces.
Step 1: Please check whether you have C:\data\db. If you dont have it create it manually.
Step 2: in command line go to directory of mongodb such as c:\Program files\Mongodb\server\3.4\bin and type *mongod
Step 3: type Mongo
Hopefully its gonna work out for you.

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.

MongoDB Data directory /data/db not found [duplicate]

This question already has answers here:
Mongod complains that there is no /data/db folder
(28 answers)
Closed 7 years ago.
When I try to run Mongod in terminal I got this message :
2015-05-14T17:33:04.554+0700 I STORAGE [initandlisten] exception in initAndListen: 29 Data directory /data/db not found., terminating
2015-05-14T17:33:04.554+0700 I CONTROL [initandlisten] dbexit: rc: 100
and running mongo command :
MongoDB shell version: 3.0.3
connecting to: test
2015-05-14T17:34:26.679+0700 W NETWORK Failed to connect to 127.0.0.1:27017, reason: errno:111 Connection refused
2015-05-14T17:34:26.681+0700 E QUERY Error: couldn't connect to server 127.0.0.1:27017 (127.0.0.1), connection attempt failed
at connect (src/mongo/shell/mongo.js:179:14)
at (connect):1:6 at src/mongo/shell/mongo.js:179
exception: connect failed
I Have tried to change permision in /var/lib/mongodb and /var/log/mongodb, but still doesnt work, and I tried to uninstall and install mongodb again, but still the same problem exist.
Anyone could help? Thanks
I'm using Ubuntu 14.04 LTS 64 bit
MongoDB needs data directory to store data.
Default path is /data/db
When you start MongoDB engine, it searches this directory which is missing in your case. Solution is create this directory and assign rwx permission to user.
If you want to change the path of your data directory then you should specify it while starting mongod server like,
mongod --dbpath /data/<path> --port <port no>
This should help you start your mongod server with custom path and port.

[Error: failed to connect to [localhost:27017]] from NodeJS to mongodb

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)

Resources