MongoServerSelectionError: connection timed out at Timeout._onTimeout - node.js

Error
MongoServerSelectionError: connection timed out
at Timeout._onTimeout (D:\NodeJS\SearchEngine\node_modules\mongodb\lib\core\sdam\topology.js:438:30)
at listOnTimeout (internal/timers.js:554:17)
at processTimers (internal/timers.js:497:7) {
reason: TopologyDescription {
type: 'Unknown',
setName: null,
maxSetVersion: null,
maxElectionId: null,
servers: Map { 'localhost:27017' => [ServerDescription] },
stale: false,
compatible: true,
compatibilityError: null,
logicalSessionTimeoutMinutes: null,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
commonWireVersion: null
}
}
Code
try {
const client = await MongoClient.connect(connection.url, usermail.config_connection)
var header = [];
const db = client.db(connection.name);
console.log(header_data.return_call_back_header(header_data.header_id_info.ecommerce));
// res.render('index.ejs', { title: header });
console.log(header);
} catch (error) {
console.error(error)
}
Config connection
const config_connection = {
connectTimeoutMS: 5000,
socketTimeoutMS: 5000,
useUnifiedTopology: true,
useNewUrlParser: true,
serverSelectionTimeoutMS: 5000,
}
URL
url:'mongodb://localhost:27017/searchEngine', name:'searchEngine',

Related

Can't Connect My Node.js To My MongoDB Locally

I tried connecting my app.js file to my local mongoDB shell
after installing the npm mongodb dependency.
This is what i'm getting
$ node app.js
MongoServerSelectionError: connect ECONNREFUSED ::1:27017
at Timeout._onTimeout (C:\Users\Dahmie Nahty\Desktop\NativeDriverProject\node_modules\mongodb\lib\sdam\topology.js:293:38)
at listOnTimeout (node:internal/timers:564:17)
at process.processTimers (node:internal/timers:507: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) {}
}
If you are using:
mongoose.connect('mongodb://localhost/Your_collection_name');
To connect to the db.
Try:
mongoose.connect('mongodb://127.0.0.1/Your_collection_name');
Instead of that, it worked for me.

Connecting mongoose to AWS documentDB

I am trying to connect a NodeJS server to an AWS documentDB cluster with TLS enabled. The NodeJS server is hosted on an EC2 instance and it's on the same VPC as the documentDB cluster. But I'm getting the following error:
{ MongoServerSelectionError: unable to get local issuer certificate
at Timeout.waitQueueMember.timer.setTimeout [as _onTimeout] (/home/ubuntu/server/node_modules/mongodb/lib/core/sdam/topology.js:438:30)
at ontimeout (timers.js:436:11)
at tryOnTimeout (timers.js:300:5)
at listOnTimeout (timers.js:263:5)
at Timer.processTimers (timers.js:223:10)
name: 'MongoServerSelectionError',
reason:
TopologyDescription {
type: 'ReplicaSetNoPrimary',
setName: null,
maxSetVersion: null,
maxElectionId: null,
servers:
Map {
'*******.cluster-****.us-east-1.docdb.amazonaws.com:27017' => [ServerDescription] },
stale: false,
compatible: true,
compatibilityError: null,
logicalSessionTimeoutMinutes: null,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
commonWireVersion: null } }
The error seems to be with the TLS certificate. But I'm passing the contents of rds-combined-ca-bundle.pem while connecting as shown in the following code:
uri = process.env.MONGODB_URI || process.env.Db_url;
options = {
user: "****",
pass: "****",
}
mongoose.set("useCreateIndex", true);
mongoose.connect(
uri,
{
useNewUrlParser: true,
useFindAndModify: false,
useUnifiedTopology: true,
sslCA: [fs.readFileSync("/home/ubuntu/rds-combined-ca-bundle.pem")],
},
err => {
if (err) {
console.log('Connection Error: ', err);
} else {
console.log(`Successfully Connected============`);
}
}
);
I've tried connecting to the mongo cluster using mongo shell on EC2 instance using
mongo --ssl --host *******.cluster-****.us-east-1.docdb.amazonaws.com:27017 \
--sslCAFile rds-combined-ca-bundle.pem --username ***** --password *****
and this is working. So, the connection to the cluster is fine, but the mongoose cannot connect.
Is there any other way to connect to documentDB using mongoose?
Can you add ssl: true ? Something like this works for me:
const mongoose = require('mongoose');
main().catch(err => console.log(err));
async function main() {
await mongoose.connect('mongodb://user:password#docdb_uri',
{
useNewUrlParser: true,
ssl: true,
sslValidate: true,
sslCA: `/usr/local/rds-combined-ca-bundle.pem`
})
}

ReplicaSetNoPrimary error although primary exists

I have recently upgraded my mongodb setup from a standalone to a replica set. It seems as the error is caused by the replica set not having a primary (ReplicaSetNoPrimary), so I checked the replica set status but it seems fine to me (only member is the primary). Note that the connection worked before upgrading to a replica set.
Connection:
const options = {
useUnifiedTopology: true,
serverSelectionTimeoutMS: 30000,
socketTimeoutMS: 75000,
keepAlive: true,
};
const client = new MongoClient(
`mongodb://${username}:${password}#localhost:27017/?authSource=admin&replicaSet=rs0&retryWrites=true`,
options,
);
await client.connect();
Error:
/home/script/node_modules/mongodb/lib/sdam/topology.js:325
const timeoutError = new error_1.MongoServerSelectionError(`Server selection timed out after ${serverSelectionTimeoutMS} ms`, this.description);
^
MongoServerSelectionError: connection <monitor> to 127.0.0.1:27017 timed out
at Timeout._onTimeout (/home/script/node_modules/mongodb/lib/sdam/topology.js:325:38)
at listOnTimeout (node:internal/timers:557:17)
at processTimers (node:internal/timers:500:7) {
reason: TopologyDescription {
type: 'ReplicaSetNoPrimary',
servers: Map(1) {
'127.0.0.1:27017' => ServerDescription {
_hostAddress: HostAddress { isIPv6: false, host: '127.0.0.1', port: 27017 },
address: '127.0.0.1:27017',
type: 'Unknown',
hosts: [],
passives: [],
arbiters: [],
tags: {},
minWireVersion: 0,
maxWireVersion: 0,
roundTripTime: -1,
lastUpdateTime: 3298259072,
lastWriteDate: 0,
topologyVersion: {
processId: ObjectId { [Symbol(id)]: [Buffer [Uint8Array]] },
counter: 6
},
error: MongoNetworkTimeoutError: connection <monitor> to 127.0.0.1:27017 timed out
at Connection.handleIssue (/home/script/node_modules/mongodb/lib/cmap/connection.js:116:23)
at Socket.<anonymous> (/home/script/node_modules/mongodb/lib/cmap/connection.js:63:41)
at Socket.emit (node:events:394:28)
at Socket._onTimeout (node:net:486:8)
at listOnTimeout (node:internal/timers:557:17)
at processTimers (node:internal/timers:500:7) {
[Symbol(beforeHandshake)]: false
}
}
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
setName: 'rs0',
maxSetVersion: 1,
maxElectionId: ObjectId {
[Symbol(id)]: Buffer(12) [Uint8Array] [
127, 255, 255, 255, 0,
0, 0, 0, 0, 0,
0, 2
]
},
commonWireVersion: 13,
logicalSessionTimeoutMinutes: undefined
}
}
Replica Set Status
rs0 [direct: primary] admin> rs.status().members
[
{
_id: 0,
name: '127.0.0.1:27017',
health: 1,
state: 1,
stateStr: 'PRIMARY',
uptime: 13174,
optime: { ts: Timestamp({ t: 1633978566, i: 89 }), t: Long("2") },
optimeDate: ISODate("2021-10-11T18:56:06.000Z"),
syncSourceHost: '',
syncSourceId: -1,
infoMessage: '',
electionTime: Timestamp({ t: 1633965396, i: 1 }),
electionDate: ISODate("2021-10-11T15:16:36.000Z"),
configVersion: 1,
configTerm: 2,
self: true,
lastHeartbeatMessage: ''
}
]

MongoServerSelectionError: connection <monitor> to 34.93.94.239:27017 closed - Nodejs

I am using MongoClient in nodejs to insert bulk records into a database. I am using async.eachOfLimit to do this in batches.
let cursor2 = await consultation_collection
.find({ processed: { $exists: false } })
.limit(limit)
.toArray();
await eachOfLimit(cursor2, 2, insertData);
However, after inserting about 50-60 records , I am constantly getting this error-
MongoServerSelectionError: connection <monitor> to 34.93.94.239:27017 closed
at Timeout._onTimeout (C:\Users\Santosh Chirag\Downloads\migrate-test\node_modules\mongodb\lib\core\sdam\topology.js:438:30)
at listOnTimeout (internal/timers.js:554:17)
at processTimers (internal/timers.js:497:7) {
reason: TopologyDescription {
type: 'ReplicaSetNoPrimary',
setName: 'atlas-bagddj-shard-0',
maxSetVersion: null,
maxElectionId: null,
servers: Map(3) {
'medv5-dev-shard-00-00.to7mj.gcp.mongodb.net:27017' => [ServerDescription],
'medv5-dev-shard-00-01.to7mj.gcp.mongodb.net:27017' => [ServerDescription],
'medv5-dev-shard-00-02.to7mj.gcp.mongodb.net:27017' => [ServerDescription]
},
stale: false,
compatible: true,
compatibilityError: null,
logicalSessionTimeoutMinutes: 30,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
commonWireVersion: 9
}
}
The code runs fine if I press enter , then it inserts 10-15 records more and this error occurs again continuously.
What is this error regarding and how to make Mongo stay connected till all the records have been inserted

NodeJS MongoDB ReplicaSetNoPrimary

I was attempting to connect to a MongoDB cluster using the following from the nodeJS MongoDB package
const client = require('mongodb').MongoClient
const conn = await client.connect(
process.env.MONGO_DSN,
{
useUnifiedTopology: true,
ssl: process.env.MONGO_SSL, // true
},
)
The MONGO_DSN variable is as follows:
mongodb://{USER}:{PASSWORD}#{HOST1}:27017,{HOST2}:27017,{HOST3}:27017/{DB_NAME}?ssl=true&replicaSet={REPLICASET}&authSource=admin&retryWrites=true&w=majority
However, the connection times out with the error
MongoServerSelectionError: connection <monitor> to {IP_ADDRESS}:27017 closed
at Timeout._onTimeout (/node_modules/mongodb/lib/core/sdam/topology.js:438:30)
at listOnTimeout (internal/timers.js:531:17)
at processTimers (internal/timers.js:475:7) {
name: 'MongoServerSelectionError',
reason: TopologyDescription {
type: 'ReplicaSetNoPrimary',
setName: null,
maxSetVersion: null,
maxElectionId: null,
servers: Map {
'{HOST1}:27017' => [ServerDescription],
'{HOST2}:27017' => [ServerDescription],
'{HOST3}:27017' => [ServerDescription]
},
stale: false,
compatible: true,
compatibilityError: null,
logicalSessionTimeoutMinutes: null,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
commonWireVersion: null
}
}
After a little playing around, I found out that I can connect successfully if I remove the ssl config option from the driver constructor and leave it to infer it from the DSN query string:
const client = require('mongodb').MongoClient
const conn = await client.connect(
process.env.MONGO_DSN,
{
useUnifiedTopology: true,
},
)
Why would this config option (not sure if others effect this too) effect the ability to connect?
Is it because if there are config options specified in the constructor that appear in the DSN, then it completely ignores the DSN query string, which would mean some config options would then be missing (primary replica)?
To clarify, there are no issues with the hosts in the DSN, no issues with connecting to the database normally, only when the config is set in the constructor.

Resources