MongooseServerSelectionError: connect ECONNREFUSED ::1:27017

Viewed 8171

I have a problem when I try to connect my app with my database with Mongoose. Already tried following solutions that I found on google:

  • restarting MongoDB service on windows
  • manually open db with cmd located on bin file of mongodb

But I can't solve it. Can anyone help me ?

//my connection
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/notes-db-app',{
    useNewUrlParser: true, 
    useUnifiedTopology: true
})
.then(db => console.log('DB is connected'))
.catch(err => console.log(err));

And throw's me , this error

MongooseServerSelectionError: connect ECONNREFUSED ::1:27017 at NativeConnection.Connection.openUri (C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\connection.js:797:32) at C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\index.js:330:10 at C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\helpers\promiseOrCallback.js:32:5 at new Promise () at promiseOrCallback (C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\helpers\promiseOrCallback.js:31:10) at Mongoose._promiseOrCallback (C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\index.js:1151:10) at Mongoose.connect (C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\index.js:329:20) at Object. (C:\Users\ivan\Desktop\NodeJS\notes-app\src\db.js:3:10)
at Module._compile (node:internal/modules/cjs/loader:1095:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1147:10) {
reason: TopologyDescription { type: 'Unknown', servers: Map(1) { 'localhost:27017' => [ServerDescription] }, stale: false, compatible: true, heartbeatFrequencyMS: 10000, localThresholdMS: 15, logicalSessionTimeoutMinutes: undefined } }

I try to put the port on my connection code like this

//my connection
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/notes-db-app',{
    useNewUrlParser: true, 
    useUnifiedTopology: true
})
.then(db => console.log('DB is connected'))
.catch(err => console.log(err));

and it throw's me another error

MongooseServerSelectionError: Invalid message size: 1347703880, max allowed: 67108864 at NativeConnection.Connection.openUri (C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\connection.js:797:32) at C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\index.js:330:10 at C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\helpers\promiseOrCallback.js:32:5 at new Promise () at promiseOrCallback (C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\helpers\promiseOrCallback.js:31:10) at Mongoose._promiseOrCallback (C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\index.js:1151:10) at Mongoose.connect (C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\index.js:329:20) at Object. (C:\Users\ivan\Desktop\NodeJS\notes-app\src\db.js:3:10)
at Module._compile (node:internal/modules/cjs/loader:1095:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1147:10) {
reason: TopologyDescription { type: 'Unknown', servers: Map(1) { 'localhost:3000' => [ServerDescription] }, stale: false, compatible: true, heartbeatFrequencyMS: 10000, localThresholdMS: 15, logicalSessionTimeoutMinutes: undefined } }

6 Answers
const uri = 'mongodb://localhost:27017/test';

const options = {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    serverSelectionTimeoutMS: 5000,
    autoIndex: false, // Don't build indexes
    maxPoolSize: 10, // Maintain up to 10 socket connections
    serverSelectionTimeoutMS: 5000, // Keep trying to send operations for 5 seconds
    socketTimeoutMS: 45000, // Close sockets after 45 seconds of inactivity
    family: 4 // Use IPv4, skip trying IPv6
}

const connectWithDB = () => {
    mongoose.connect(uri, options, (err, db) => {
      if (err) console.error(err);
      else console.log("database connection")
    })
}

connectWithDB()

I finally solved it.

Enabling the IPV6 that MongoDB has disabled by default. Using the following command line on CMD:

mongod --ipv6 

And then try again the connection and it works!

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/notes-db-app',{
    useNewUrlParser: true, 
    useUnifiedTopology: true
})
.then(db => console.log('DB is connected'))
.catch(err => console.log(err));

Posted on behalf of the question asker

Simply pass third parameter family:4 ie.

mongoose.connect('mongodb://localhost/notes-db-app',{
    useNewUrlParser: true, 
    useUnifiedTopology: true,
    family: 4,
})

If the Error states:

connect() Error :MongooseServerSelectionError: connect ECONNREFUSED ::1:27017

Then the connection to localhost is refused on the IPv6 address ::1 . Mongoose per default uses IPv6 ..

For a quick check you can set the IPv4 address explicit:

mongoose.connect('mongodb://127.0.0.1/test')

Probably the hostname/IP of the server to which you want to connect is not correctly set.
I'm used to see that error as:

MongooseServerSelectionError: connect ECONNREFUSED <hostname/hostIP>:<port>

and in the console log you've posted, the <hostname/hostIP> part is malformed/missing.

Example - for a mongodb server running locally on port 27017 this is the error when server is down:

MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017

If you're using mongodb URI to connect to the db make sure that it looks like this

"mongodb://<hostname/hostIP>:<port>"
  1. Open your terminal and type this command: mongod
  2. Then use your app.js to establish a connection by writing this code :
    const mongoose=require("mongoose");
    mongoose.connect('mongodb://localhost/notes-db-app',{
        useNewUrlParser: true, 
        useUnifiedTopology: true,
        family: 4,
    })
    
  3. It's done now. Simply open your mongo shell or your mongodb compass and look for whatever you have added.
Related