ReplicaSetNoPrimary when attempting to connect from node

I set up a MongoDB database to use with a simple node.js project I created many months ago and it was working fine back then. I can still connect to it and query it from the command line just fine (using the mongo CLI) but cannot seem to connect to it from within node. When I use this code to connect:

import MongoClient from 'mongodb';
const mongoUrl = 'mongodb://localhost/my-project?replicaSet=rs0';
MongoClient.connect(mongoUrl, { useUnifiedTopology: true }).then(() => {
    console.log('success');
}).catch(e => {
    console.error(e);
    process.exit(1);
});

I encounter this error message:

MongoServerSelectionError: connect ECONNREFUSED ::1:27017
    at Timeout._onTimeout (/srv/http/bugs/private/node_modules/mongodb/lib/core/sdam/topology.js:438:30)
    at listOnTimeout (node:internal/timers:568:17)
    at processTimers (node:internal/timers:510:7) {
  reason: TopologyDescription {
    type: 'ReplicaSetNoPrimary',
    setName: null,
    maxSetVersion: null,
    maxElectionId: null,
    servers: Map(1) { 'localhost:27017' => [ServerDescription] },
    stale: false,
    compatible: true,
    compatibilityError: null,
    logicalSessionTimeoutMinutes: null,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    commonWireVersion: null
  }
}

I found this similar question when searching for solutions, but I don’t think their fix makes sense for me. I have a very simple setup with mongo and node running on the same machine. I don’t entirely remember why I set up replication, but it was only because of some sort of warning I had encountered back when I set this up. The contents of the database are not important, so I don’t mind if the data gets destroyed, I’d just like to be able to connect to mongo from node again. Thanks in advance for any help!

1 Like

After fiddling around sufficiently I discovered that my code works again if I replace “localhost” with “127.0.0.1”. Specifically, this is what works:

import MongoClient from 'mongodb';
const mongoUrl = 'mongodb://127.0.0.1/my-project?replicaSet=rs0';
MongoClient.connect(mongoUrl, { useUnifiedTopology: true }).then(() => {
    console.log('success');
}).catch(e => {
    console.error(e);
    process.exit(1);
});

I would still appreciate an explanation if anyone can enlighten me as to why this change is necessary. My system doesn’t seem to have any trouble resolving localhost to 127.0.0.1, so I’m baffled that this works.

1 Like

Another thread discusses same error

MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017

I think latest node.js does not support localhost
As per stackoverflow and other forums it may be due to IPV6 vs IPV4 address

Hi @Altay welcome to the community!

Are you using Windows? I found a case that may be related in NODE-868 (from 2016), which pointed to Windows DNS resolution issues as the culprit.

Since I believe drivers rely on the OS for DNS resolution, I would suspect that the cause is from the OS itself.

If not, could you please tell us your OS, and whether do you see this issue if you’re connecting from the mongo shell or another driver (e.g. Python)?

Best regards
Kevin

This makes sense to me. I guess there must have been an update to node.js that changed localhost from 127.0.0.1 to ::1. Although when I change the mongo client to mongodb://[::1]/my-project?replicaSet=rs0 I do get a different error message:

MongoServerSelectionError: connect ECONNREFUSED ::1:27017
    at Timeout._onTimeout (/srv/http/bugs/private/node_modules/mongodb/lib/core/sdam/topology.js:438:30)
    at listOnTimeout (node:internal/timers:568:17)
    at processTimers (node:internal/timers:510:7) {
  reason: TopologyDescription {
    type: 'ReplicaSetNoPrimary',
    setName: null,
    maxSetVersion: null,
    maxElectionId: null,
    servers: Map(1) {
      '::1:27017' => ServerDescription {
        address: '::1:27017',
        error: Error: connect ECONNREFUSED ::1:27017
            at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1157:16) {
          name: 'MongoNetworkError'
        },
        roundTripTime: -1,
        lastUpdateTime: 2176377029,
        lastWriteDate: null,
        opTime: null,
        type: 'Unknown',
        topologyVersion: undefined,
        minWireVersion: 0,
        maxWireVersion: 0,
        hosts: [],
        passives: [],
        arbiters: [],
        tags: []
      }
    },
    stale: false,
    compatible: true,
    compatibilityError: null,
    logicalSessionTimeoutMinutes: null,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    commonWireVersion: null
  }
}

So there’s probably more to it than that.

No, this is on Arch Linux.

I don’t see the issue when connecting from the mongo shell or from Python. Only node.js seems to have a problem resolving localhost.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.