Can’t connect to MongoDB 6.0 Server locally using Nodejs driver

Problem is, the localhost alias resolves to IPv6 address ::1 instead of 127.0.0.1

However, net.ipv6 defaults to false.

The best option would be to start the MongoDB with this configuration:

net:
  ipv6: true
  bindIpAll: true

or

net:
  ipv6: true
  bindIp: localhost

Then all variants should work:

C:\>mongosh "mongodb://localhost:27017" --quiet --eval "db.getMongo()"
mongodb://localhost:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.6.0

C:\>mongosh "mongodb://127.0.0.1:27017" --quiet --eval "db.getMongo()"
mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.6.0

C:\>mongosh "mongodb://[::1]:27017" --quiet --eval "db.getMongo()"
mongodb://[::1]:27017/?directConnection=true&appName=mongosh+1.6.0

If you don’t run MongoDB as a service then it would be

mongod --bind_ip_all --ipv6 <other options>

NB, I don’t like configuration

net:
  bindIp: <ip_address>

in my opinion this makes only sense on a computer with multiple network interfaces. Use bindIp: localhost if you need to prevent any connections from remote computer (e.g. while maintenance or when used as backend database for a web-service), otherwise use bindIpAll: true

Leave a Comment