Search code examples
node.jsmongodblocalhost

MongoDB doesn't not connect with "localhost"


Why does my MongoDB database connect using an URL that contains 127.0.0.1 instead of using 'localhost' as default, even though it doesn't work when I try to use 'localhost'? Here's the error i get:


MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
 {
  reason: TopologyDescription {
    type: 'Unknown',
    servers: Map(1) {
      'localhost:27017' => ServerDescription {
        address: 'localhost:27017',
        type: 'Unknown',
        hosts: [],
        passives: [],
        arbiters: [],
        tags: {},
        minWireVersion: 0,
        maxWireVersion: 0,
        roundTripTime: -1,
        lastUpdateTime: 79726509,
        lastWriteDate: 0,
        error: MongoNetworkError: connect ECONNREFUSED ::1:27017
            at connectionFailureError (C:\Users\...\connect.js:379:20)
            at Socket.<anonymous> (C:\Users\...\connect.js:285:22)
            at Object.onceWrapper (node:events:628:26)
            at Socket.emit (node:events:513:28)
            at emitErrorNT (node:internal/streams/destroy:151:8)
            at emitErrorCloseNT (node:internal/streams/destroy:116:3)
            at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
          [Symbol(errorLabels)]: Set(1) { 'ResetPool' },
          [cause]: Error: connect ECONNREFUSED ::1:27017
              at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494:16) {
            errno: -4078,
            code: 'ECONNREFUSED',
            syscall: 'connect',
            address: '::1',
            port: 27017
          }
        },
        topologyVersion: null,
        setName: null,
        setVersion: null,
        electionId: null,
        logicalSessionTimeoutMinutes: null,
        primary: null,
        me: null,
        '$clusterTime': null
      }
    },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    setName: null,
    maxElectionId: null,
    maxSetVersion: null,
    commonWireVersion: 0,
    logicalSessionTimeoutMinutes: null
  },
  code: undefined
}

Node.js v18.16.0

I tried disabling the firewall for public and private networks, and it still doesn't work. The moment I replace 'localhost' in the URL i use in the code to connect to the database with the IP 127.0.0.1, the database seems to connect.


Solution

  • This seems like an IPv6 issue. Most likely, localhost is initially parsed as an IPv6 address (::1), and node.js doesn't try again when that fails. When you specify the IPv4 address 127.0.0.1, the connection works on the first try.