MongoServerSelectionError: connect ECONNREFUSED 127.0.0.1:27107 - node.js

I am currently testing out MongoDB(4.4) Drivers with nodeJS(no mongoose) and trying to connect to localhost:27107. The code below is pretty much copy/paste from the official documentation test code. MongoDB is nicely running in the back.
However, on my command line I get error messages seen as below. Could anyone help me with solving this?
error message:
MongoServerSelectionError: connect ECONNREFUSED 127.0.0.1:27107
at Timeout._onTimeout (/Users/miya/Desktop/FruitsProject/node_modules/mongodb/lib/core/sdam/topology.js:438:30)
at listOnTimeout (internal/timers.js:557:17)
at processTimers (internal/timers.js:500:7) { reason: TopologyDescription {
type: 'Single',
setName: null,
maxSetVersion: null,
maxElectionId: null,
servers: Map(1) { 'localhost:27107' => [ServerDescription] },
stale: false,
compatible: true,
compatibilityError: null,
logicalSessionTimeoutMinutes: null,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
commonWireVersion: null } }
My code in app.js looks like this;
const { MongoClient } = require("mongodb");
// Connection URI
const uri =
"mongodb://localhost:27107";
// Create a new MongoClient
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
async function run() {
try {
// Connect the client to the server
await client.connect();
// Establish and verify connection
await client.db("admin").command({ ping: 1 });
console.log("Connected successfully to server");
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);
const dbName = "fruitDB";
Thanks in advance!

this thing happens most of the time may be there is Ip restriction issues or anyother to resolve this issue there are two ways
use mongoose instead of mongodb lib
here is the code for connection
var mongoose = require('mongoose');
var mongoDB = 'mongodb://127.0.0.1/my_database';
mongoose.connect(mongoDB, {useNewUrlParser: true, useUnifiedTopology: true});
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
2)if you are using atlas then use the connection string for 2 or lower nodejs version

Related

I'm getting a timeout error and topology error what to do?

i want to start a local database using mongodb. so I started creating a database using native nodejs driver. but when i run the server then there is a problem that exits. please guide me. thank you
Connection code:
const { MongoClient } = require('mongodb'); // Connection URI
const uri = 'mongodb://localhost:27017/'; // Create a new MongoClient
const client = new MongoClient(uri);
async function run() {
try {
// Connect the client to the server (optional starting in v4.7)
await client.connect(); // Establish and verify connection
await client.db('fruitsDB').command({ ping: 1 });
console.log('Connected successfully to server');
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);
MongoServerSelectionError: connect ECONNREFUSED ::1:27017
at Timeout._onTimeout (C:\Users\mskga\Desktop\fruitsproject\node_modules\mongodb\lib\sdam\topology.js:284:38)
at listOnTimeout (node:internal/timers:569:17)
at process.processTimers (node:internal/timers:512:7) { 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, [Symbol(errorLabels)]: Set(0) {} }
this is the error that I'm getting so please tell me what is the error exactly and how to rectify it
Change the host value from localhost to 127.0.0.1.
const uri = 'mongodb://127.0.0.1:27017

I am getting the following error while connecting mongodb to node.js. please solve the issue [duplicate]

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
}
}
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')
Simply pass third parameter family:4 ie.
mongoose.connect('mongodb://localhost/notes-db-app',{
useNewUrlParser: true,
useUnifiedTopology: true,
family: 4,
})
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
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()
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>"
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
Open your terminal and type this command: mongod
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,
})
It's done now. Simply open your mongo shell or your mongodb compass and look for whatever you have added.
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

AWS Lambda connecting DocumentDb instance got MongoServerSelectionError: getaddrinfo EAI_AGAIN

Got following error logs when trying to connecting lambda to documentdb.
TART RequestId: 0946e4e9-9364-4af2-9802-7ea2d8b946d5 Version: $LATEST
2021-08-18T16:25:11.958Z 0946e4e9-9364-4af2-9802-7ea2d8b946d5 INFO insideHandler
2021-08-18T16:25:42.296Z 0946e4e9-9364-4af2-9802-7ea2d8b946d5 ERROR MongoServerSelectionError: getaddrinfo EAI_AGAIN sample-dev-01-instance1.abcde.us-east-1.docdb.amazonaws.com
at Timeout._onTimeout (/var/task/node_modules/mongodb/lib/sdam/topology.js:325:38)
at listOnTimeout (internal/timers.js:557:17)
at processTimers (internal/timers.js:500:7) {
reason: TopologyDescription {
type: 'Unknown',
servers: Map(1) {
'sample-dev-01-instance1.abcde.us-east-1.docdb.amazonaws.com:27017' => [ServerDescription]
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
logicalSessionTimeoutMinutes: undefined
}
}
the VPC of lambda is the same as documentdb instance. The nodejs code connects the instance successfully when running in local but has the issue in lambda.
const { MongoClient } = require('mongodb');
exports.handler = async(event, context) => {
console.log("insideHandler");
const uri = 'mongodb://username:password#sample-dev-01-instance1.abcde.us-east-1.docdb.amazonaws.com:27017';
const client = new MongoClient(uri, {
useNewUrlParser: true,
ssl: true,
tlsCAFile: `rds-combined-ca-bundle.pem`, //Specify the DocDB; cert
retryWrites: false
});
try {
await client.connect();
console.log("connect successfully");
return {
statusCode: 200,
body: JSON.stringify({ message: 'connect successfully' })
}
}
catch (e) {
console.error(e);
}
};
enter code here
EAI_AGAIN is a DNS lookup timed out error, means it is a network connectivity error or proxy related error. Can you confirm whether the Lambda function is using the same security group as the DocumentDB cluster?

Connection error between nodejs and mongodb atlas using mongoose

I am trying to build a backend app using mongodb atlas. I have followed the instruction but I got error like this
{ MongooseServerSelectionError: connect ECONNREFUSED 18.140.224.177:27017
at new MongooseServerSelectionError
...
message: 'connect ECONNREFUSED 18.140.224.177:27017',
name: 'MongooseServerSelectionError',
reason:
TopologyDescription {
type: 'ReplicaSetNoPrimary',
setName: null,
maxSetVersion: null,
maxElectionId: null,
servers:
Map {
'database-shard-00-01-ayo9w.mongodb.net:27017' => [ServerDescription],
'database-shard-00-00-ayo9w.mongodb.net:27017' => [ServerDescription],
'database-shard-00-02-ayo9w.mongodb.net:27017' => [ServerDescription]
stale: false,
compatible: true,
compatibilityError: null,
logicalSessionTimeoutMinutes: null,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
commonWireVersion: null },
[Symbol(mongoErrorContextSymbol)]: {} }
and here is my code
const mongoose = require('mongoose');
mongoose.connect("mongodb+srv://thanh:Abcdefghijk#database-ayo9w.mongodb.net/test?retryWrites=true&w=majority",
{ useNewUrlParser: true, useUnifiedTopology: true, },
).then(() => console.log('Connected to database')).
catch(err => console.log('Error in connection', err));
My whitelist entry in mongodb atlas is 0.0.0.0/0
Change username and password with your database username and password. Check mongoDB Atlas where you have created your database and collections.
The reason for this is the internet connection. I just change my wifi connection and it works. This is the link where I get the answer
Error at connecting to MongoDb Atlas Server
Your network or hosting has port 27017 blocked, that's why you can't access server.
To test if the port is blocked you can try this on terminal on mac/linux
(curl portquiz.net:27017) or on cmd (nc -v portquiz.net 27017)
This should solve your issue.

Mongoose Replicaset Connection Not Working

I am trying to connect to AWS MongoDB instances and its not even attempting to connect:
This is the connection URI:
mongodb://<usr>:<pwd>#host:port,host2:port2/db
And this is the code I am using to connect.
var mongoose = require('mongoose');
var dbOptions = { server: { socketOptions: { keepAlive: 300000, connectTimeoutMS: 30000 } },
replset: { socketOptions: { keepAlive: 300000, connectTimeoutMS : 30000 } } };
mongoose.connect(uri, dbOptions);
I also added logs inside events.. none of the events are firing. If I remove host2:port2 it works. So issue seems to be with the connection string. But connection string looks totally fine.. but still its not working.. Any idea why?

Resources