I'm using NodeJS wih MongoDB using mongodb package. When I run mongod command it works fine and gives "waiting for connection on port 27017". So, mongod seems to be working. But MongoClient does not work and gives error when I run node index.js command-
MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]
I have install mongo db 3.4 and my code is-
var MongoClient = require('mongodb').MongoClient; var dburl = "mongodb://localhost:27017/test"; MongoClient.connect(dburl, function(err, db) { if (err) { throw err; } console.log('db connected'); db.close(); });
I have created data/db directories on root and given write permissions. mongod.conf file takes db path as-
storage: dbPath: /var/lib/mongo
But it seems that it is actually taking db path as data/db and not var/lib/mongo
It working earlier but suddenly stopped.
ECONNREFUSED error means that connection could not be made with the target service (in your case localhost:8080 ). Check your service running on port 8080.
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.
This happened probably because the MongoDB service isn't started. Follow the below steps to start it:
The server will start. Now execute npm start
again and the code might work this time.
For windows - just go to Mongodb folder (ex : C:\ProgramFiles\MongoDB\Server\3.4\bin) and open cmd in the folder and type "mongod.exe --dbpath c:\data\db"
if c:\data\db folder doesn't exist then create it by yourself and run above command again.
All should work fine by now.))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With