MongoServerSelectionError: connect ECONNREFUSED ::1:27017

Hello all,

New to Mongo so I’ll do my best to provide as many details as possible to solve my issue. I’ve searched this forum but nothing presented any solutions.

Installed MongoDB Community 5.0.6 via the tarball to the location of /usr/local/mongodb on an Intel Mac running OS Big Sur 11.6.5
Launched the db with mongod --dbpath ~/data/db

Connecting to db with mongo shell and MongoDB Compass worked flawlessly. I can connect to dbs, create dbs/collections, modify data, etc.

My issue is trying to connect using the official mongodb 4.5.0 node package. I’ve stripped down the code only trying to connect() with code taken directly from Mongo’s official YouTube demo.

const { MongoClient } = require('mongodb')

async function main() {
  const url = 'mongodb://localhost:27017'

  const client = new MongoClient(url)

  try {
    await client.connect()
  } catch (e) {
  } finally {
    await client.close()


Running the code returns the following error:

MongoServerSelectionError: connect ECONNREFUSED ::1:27017
    at Timeout._onTimeout (/Users/jimhall/blog-backend/node_modules/mongodb/lib/sdam/topology.js:318:38)
    at listOnTimeout (node:internal/timers:568:17)
    at processTimers (node:internal/timers:510:7) {
  reason: TopologyDescription {
    type: 'Unknown',
    servers: Map(1) { 'localhost:27017' => [ServerDescription] },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    logicalSessionTimeoutMinutes: undefined
  code: undefined,
  [Symbol(errorLabels)]: Set(0) {}

I’ve not modified any configuration options other than using the --dbpath as using /data/db was not allowed. I’ve tried rolling back the node package to version 4.4.1 as well as trying MongoDB version 4.4 but no luck there either.

Thanks in advance for any help,

Try with rather than localhost:27017.

Looks like localhost is not resolved correctly.

1 Like

I’ve tried that multiple times, swapping the loopback ip for localhost, it never worked. But for some reason now that you said it, it worked. Almost didn’t try again because of that. Wonder why localhost is not recognized. It works fine using it elsewhere.

1 Like

May be it is only defined for IPv6.

Take a peek in /etc/hosts.

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