Published: June 09 2023

Fix for MongooseServerSelectionError: connect ECONNREFUSED ::1:27017

Just ran into this error after updating from Node 16 to Node 18 and tried to run this Next.js + MongoDB project.

error - unhandledRejection: MongooseServerSelectionError: connect ECONNREFUSED ::1:27017


This is the full stack trace with the error, the project uses Mongoose to connect to MongoDB.

MongooseError: Operation `users.findOne()` buffering timed out after 10000ms
    at Timeout.<anonymous> (C:\_Home\Projects\next\next-js-13-mongodb-registration-login-example\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:185:23)
    at listOnTimeout (node:internal/timers:564:17)
    at process.processTimers (node:internal/timers:507:7)
error - unhandledRejection: MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
    at _handleConnectionErrors (C:\_Home\Projects\next\next-js-13-mongodb-registration-login-example\node_modules\mongoose\lib\connection.js:755:11)
    at NativeConnection.openUri (C:\_Home\Projects\next\next-js-13-mongodb-registration-login-example\node_modules\mongoose\lib\connection.js:730:11) {
  reason: TopologyDescription {
    type: 'Unknown',
    servers: Map(1) { 'localhost:27017' => [ServerDescription] },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    setName: null,
    maxElectionId: null,
    maxSetVersion: null,
    commonWireVersion: 0,
    logicalSessionTimeoutMinutes: null
  },
  code: undefined
}


Cause of the MongoDB connection error

After a bit of digging I found out the error was caused by my connection string:

connectionString: "mongodb://localhost/next-js-registration-login-example"


Node now prefers IPv6 to IPv4 since v17

A change in Node v17 makes the preferred IP address for localhost the IPv6 address (::1). Up until Node v16 it preferred the IPv4 address for localhost (127.0.0.1).


Fix for the error

To fix the issue I just had to change the connection string to connect to the IPv4 address 127.0.0.1 instead of localhost:

connectionString: "mongodb://127.0.0.1/next-js-registration-login-example"

 


Need Some MongoDB Help?

Search fiverr for freelance MongoDB developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by