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?