14

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 (<anonymous>)
    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.<anonymous> (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 (<anonymous>)
    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.<anonymous> (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
  }
}
Wernfried Domscheit
  • 54,457
  • 9
  • 76
  • 110
InthraDev
  • 141
  • 1
  • 1
  • 4
  • Make sure that Mongodb is running, open task scheduler look for mongo, if You're doing it from linux subsystem so: `ps -ax | grep mongo` – num8er Nov 04 '21 at 14:50
  • OP did that already and is using windows – DarkBee Nov 04 '21 at 14:51
  • Does this answer your question? [MongooseServerSelectionError: connect ECONNREFUSED ::1:27017 wont get fixed](https://stackoverflow.com/questions/69763130/mongooseserverselectionerror-connect-econnrefused-127017-wont-get-fixed) – Joe Nov 04 '21 at 15:59
  • Please post the solution as an answer. Do not edit the question – Dharman Nov 05 '21 at 17:59

8 Answers8

29

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')
Alex
  • 299
  • 3
  • 2
  • 1
    awesome! It solved the problem. – The Mir Sep 05 '22 at 19:05
  • Cool, that actually runs the db connection properly. However, what causes this error? On my laptop, the connection starts with `localhost`, but using my PC, it requires to run it with `127.0.0.1`. I want to find what is not configured properly. The only difference is that the laptop is using Win10, but the PC is using Win11 – Vitomir Jan 23 '23 at 13:22
  • I don't think Mongoose is the culprit. Alias `localhost` is resolved by the operating system – Wernfried Domscheit Jan 25 '23 at 16:07
  • That's is the correct solution. – overdd Jul 20 '23 at 08:17
9

Simply pass third parameter family:4 ie.

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

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

Dharman
  • 30,962
  • 25
  • 85
  • 135
  • It was exactly more than 2 days I was struggling to figure out what is the problem in my connection then I saw your suggestion I mean using "--ipv6" in mongod command and it was absolutely what I needed, Perfect thanks and really appreciate. actually I edited my command to mongod --dbpath /data/db --replSet "rs" and it works perfectly like a charm. ;) – Sina.Moradbakhti Jan 17 '22 at 07:13
6
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()
RS Shonjoy
  • 245
  • 3
  • 2
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 01 '21 at 01:17
1

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 will work:

mongoose.connect('mongodb://localhost:27017',{
    useNewUrlParser: true, 
    useUnifiedTopology: true
})

mongoose.connect('mongodb://127.0.0.1:27017',{
    useNewUrlParser: true, 
    useUnifiedTopology: true
})

mongoose.connect('mongodb://[::1]:27017',{
    useNewUrlParser: true, 
    useUnifiedTopology: true
})

mongoose.connect(`mongodb://${os.hostname()}:27017`,{
    useNewUrlParser: true, 
    useUnifiedTopology: true
})

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 however, MongoDB does not support multiple 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

Wernfried Domscheit
  • 54,457
  • 9
  • 76
  • 110
0

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>"
Dharman
  • 30,962
  • 25
  • 85
  • 135
8ns
  • 129
  • 8
-1

I also faced the same problem those commands worked for me(Ubuntu machine)

sudo chown -R mongodb:mongodb /var/lib/mongodb
sudo chown mongodb:mongodb /tmp/mongodb-27017.sock

Then

sudo service mongod restart
MD Jahid Hasan
  • 786
  • 1
  • 9
  • 19
-2
  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.
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Shishir Jha
  • 1
  • 1
  • 3