ReplicaSetNoPrimary error although primary exists - node.js

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: ''
}
]

Related

Connect ECONNREFUSED 127.0.0.1:27017 in Mongodb

Hello I am new to MongoDB. I am trying to Connect to MongoDb with 'mongodb://localhost:27017' but not connecting. However I try to enter with MongoDb Compass and mongosh shell command it is working.
The error codes are
node app.js
node:internal/process/promises:288
triggerUncaughtException(err, true /* fromPromise */);
^
AssertionError [ERR_ASSERTION]: null == MongoServerSelectionError: connect ECONNREFUSED ::1:27017
at Timeout._onTimeout (C:\Users\kokophone\Documents\MEGAsync\Mystudy\Web\Udemy\Angela Bootcamp\Mgphone One\MangoDB\FruitProject\node_modules\mongodb\lib\sdam\topology.js:292:38)
at listOnTimeout (node:internal/timers:564:17)
at process.processTimers (node:internal/timers:507:7) {
[Symbol(errorLabels)]: Set(0) {},
code: undefined,
reason: TopologyDescription {
commonWireVersion: 0,
compatible: true,
heartbeatFrequencyM...
at C:\Users\kokophone\Documents\MEGAsync\Mystudy\Web\Udemy\Angela Bootcamp\Mgphone One\MangoDB\FruitProject\app.js:15:10
at C:\Users\kokophone\Documents\MEGAsync\Mystudy\Web\Udemy\Angela Bootcamp\Mgphone One\MangoDB\FruitProject\node_modules\mongodb\lib\utils.js:349:66 {
generatedMessage: true,
code: 'ERR_ASSERTION',
actual: null,
expected: MongoServerSelectionError: connect ECONNREFUSED ::1:27017
at Timeout._onTimeout (C:\Users\kokophone\Documents\MEGAsync\Mystudy\Web\Udemy\Angela Bootcamp\Mgphone One\MangoDB\FruitProject\node_modules\mongodb\lib\sdam\topology.js:292: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 {
address: 'localhost:27017',
type: 'Unknown',
hosts: [],
passives: [],
arbiters: [],
tags: {},
minWireVersion: 0,
maxWireVersion: 0,
roundTripTime: -1,
lastUpdateTime: 2313988,
lastWriteDate: 0,
error: MongoNetworkError: connect ECONNREFUSED ::1:27017
at connectionFailureError (C:\Users\kokophone\Documents\MEGAsync\Mystudy\Web\Udemy\Angela Bootcamp\Mgphone One\MangoDB\FruitProject\node_modules\mongodb\lib\cmap\connect.js:387:20)
at Socket.<anonymous> (C:\Users\kokophone\Documents\MEGAsync\Mystudy\Web\Udemy\Angela Bootcamp\Mgphone One\MangoDB\FruitProject\node_modules\mongodb\lib\cmap\connect.js:310:22)
at Object.onceWrapper (node:events:628:26)
at Socket.emit (node:events:513:28)
at emitErrorNT (node:internal/streams/destroy:151:8)
at emitErrorCloseNT (node:internal/streams/destroy:116:3)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
cause: [Error],
[Symbol(errorLabels)]: [Set]
},
topologyVersion: null,
setName: null,
setVersion: null,
electionId: null,
logicalSessionTimeoutMinutes: null,
primary: null,
me: null,
'$clusterTime': null
}
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
setName: null,
maxElectionId: null,
maxSetVersion: null,
commonWireVersion: 0,
logicalSessionTimeoutMinutes: null
},
code: undefined,
[Symbol(errorLabels)]: Set(0) {}
},
operator: '=='
}
Node.js v18.12.1
please help me out.
Change localhost by 0.0.0.0. in the source code .
const url = "mongodb://localhost:27017/";
const client = new MongoClient(url);
to
const url = "mongodb://0.0.0.0:27017/";
const client = new MongoClient(url);

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.

Running into a problem starting up mongoDB

I downloaded MongoDB with Compass and the shell as accessories and started learning from W3Schools Node.js MongoDB section.
Step 1: type into command prompt>npm install mongodb
success
step 2: create a MongoClient object file with this code and then save
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
console.log("Database created!");
db.close();
});
Step 3: Once the code above is saved run the file by calling it on the command prompt
C:\Users\MyName>node fileName.js
and this is the response I'm getting
C:\Users\*****\MongoDB Tutorials>node demo_create_mongo_db.js
C:\Users\*****\node_modules\mongodb\lib\utils.js:418
throw error;
^
MongoServerSelectionError: connect ECONNREFUSED ::1:27017
at Timeout._onTimeout (C:\Users\*****\node_modules\mongodb\lib\sdam\topology.js:293:38)
at listOnTimeout (node:internal/timers:557:17)
at processTimers (node:internal/timers:500:7) {
reason: TopologyDescription {
type: 'Unknown',
servers: Map(1) {
'localhost:27017' => ServerDescription {
_hostAddress: HostAddress { isIPv6: false, host: 'localhost', port: 27017 },
address: 'localhost:27017',
type: 'Unknown',
hosts: [],
passives: [],
arbiters: [],
tags: {},
minWireVersion: 0,
maxWireVersion: 0,
roundTripTime: -1,
lastUpdateTime: 11442648,
lastWriteDate: 0,
error: MongoNetworkError: connect ECONNREFUSED ::1:27017
at connectionFailureError (C:\Users\*****\node_modules\mongodb\lib\cmap\connect.js:379:20)
at Socket.<anonymous> (C:\Users\*****\node_modules\mongodb\lib\cmap\connect.js:302:22)
at Object.onceWrapper (node:events:510:26)
at Socket.emit (node:events:390:28)
at emitErrorNT (node:internal/streams/destroy:164:8)
at emitErrorCloseNT (node:internal/streams/destroy:129:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
[Symbol(errorLabels)]: Set(0) {}
}
}
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
logicalSessionTimeoutMinutes: undefined
},
code: undefined,
[Symbol(errorLabels)]: Set(0) {}
}
Node.js v17.2.0
What do I do about this?

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

MongoServerSelectionError: connection timed out at Timeout._onTimeout

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',

Resources