Sharma Ankush
Sharma Ankush

Reputation: 321

MongoServerSelectionError: connect ECONNREFUSED ::1:27017

I am using Mongo 5.0.1 and Node 17.2.0 this is my code If I connect want to connect with Atlas with this code it runs successfully but when I try to connect with the local Database it gives this error.

const { MongoClient } = require("mongodb");

async function main(){
    const uri = "mongodb://localhost:27017";

    const client = new MongoClient(uri);

    try{
        await client.connect();
        await listDatabases(client);
    } catch (e){
        console.error(e);
    } finally {
        await client.close();
    }
}
main().catch(console.error);

async function listDatabases(client) {
    databasesList = await client.db().admin().listDatabases();

    console.log("Databases:");
    databasesList.databases.forEach(db => console.log(` - ${db.name}`));
};

This is the error I am getting.

MongoServerSelectionError: connect ECONNREFUSED ::1:27017
    at Timeout._onTimeout (D:\web development\nodeDemo\node_modules\mongodb\lib\sdam\topology.js:330:38)
    at listOnTimeout (node:internal/timers:557:17)
    at processTimers (node:internal/timers:500:7) {
  reason: TopologyDescription {
    type: 'Unknown',
    servers: Map(1) { 'localhost:27017' => [ServerDescription] },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    logicalSessionTimeoutMinutes: undefined
  }
}

Upvotes: 7

Views: 6054

Answers (5)

Sharma Ankush
Sharma Ankush

Reputation: 321

Use this as your URI

  const uri = "mongodb://127.0.0.1:27017";

Upvotes: 14

Muhammad Ammar Nazir
Muhammad Ammar Nazir

Reputation: 11

I simply replaced localhost with my IP Address 127.0.0.1 and it works

Syntax: const dbURI = "mongodb://127.0.0.1:27017/MyDB";

Upvotes: 1

saleem
saleem

Reputation: 415

in my case, I simply replaced the connection string from 'mongodb://localhost/MyDBName' with 'mongodb://127.0.0.1:27017/MyDBName'. Also, please ensure that the MongoDB server is up and running.

enter image description here

Upvotes: 0

mnavasp
mnavasp

Reputation: 1

Use this URL:

mongodb://127.0.0.1:27017

Instead of:

mongodb://localhost:27017

Upvotes: 0

andreacanton
andreacanton

Reputation: 383

I solved this by enabling the IPv6 in the mongodb.config

more info here https://www.mongodb.com/docs/manual/reference/configuration-options/#mongodb-setting-net.ipv6

Upvotes: 2

Related Questions