I’m facing an issue while trying to connect to MongoDB from my Node.js application using the mongodb driver.
I have a MongoDB server running on my local machine, and I can successfully connect to it using MongoDB Compass and the VS Code extension.
However, when I attempt to connect from my Node.js application, I encounter an error.
const { MongoClient } = require('mongodb');
const uri = 'mongodb://localhost:27017/';
const client = new MongoClient(uri);
client.connect((err) => {
if (err) {
console.error(err);
return;
}
console.log('Connected to MongoDB');
// ... continue with my code
});
The error message I receive is:
MongoServerSelectionError: connect ECONNREFUSED ::1:27017
// rest of the error details...
I was try to connect to MongoDB from a Node.js app.
I have already checked the following:
- The MongoDB server is running on my local machine, and I can connect using MongoDB Compass and VS Code extension.
- I have installed the mongodb package using npm, and I tried different versions of the package as well.
- There is no authentication required to connect to my MongoDB server.
- I have also tried specifying the version of the mongodb package during installation, but the issue persists.
Why I can’t connect to MongoDB from my Node.js application? Am I missing something in my code or configuration?
2
Answers
hi everyone thank you all for your helpful comments, the answer to this problem is in two steps
A. set them in mongod.conf file
or
B. just add them to the command when starting Mongo server
mongod --bind_ip_all --ipv6
the first two and are enabled the others are optional
also I would refer to this problem as it's like mine Can't connect to MongoDB 6.0 Server locally using Nodejs driver
Try replacing
localhost
in the URI by explicit locsl IPv4127.0.0.1
:As explained on mongodb driver for Node: