Mongoose cannot connect to a single replica set at first connection - node.js

I create a MongoDB replica set by using flag --replSet rs. the rs.status() works fine and the mongo-express can access that replica.
But when I try to use :
let options = {
"replset": {
"rs_name": "rs"
}
}
mongoose.connect('mongodb://localhost:27017/tasksDB', options);
to connect the mongodb. It throws out:
failed to connect to server [91891b77b79f:27017] on first connect [MongoNetworkError: getaddrinfo ENOTFOUND 91891b77b79f 91891b77b79f:27017]'
If I remove the options to connect without replset option. It works fine.
I'd trid another way to connect the mongodb: ?replicaSet=rs, still not working.

Related

MongooseServerSelectionError: connect ECONNREFUSED ::1:27017 in mongoose6.1.13

I'm using NodeJS with MongoDB using MongoDB package. When I run mongod command it works fine and gives "waiting for connection on port 27017". So, mongod seems to be working. But MongoClient does not work and gives an error when I run node index.js code.
The error is given below in the picture.
I have installed mongo DB 5.0.5, mongoose package 6.1.13 and my code is-
// getting-started.js
const mongoose = require('mongoose');
main().catch(err => console.log(err));
async function main() {
await mongoose.connect('mongodb://localhost:27017/test');
}
I'm able to connect the database by console log and windows power shell but not by the node.js
Error description

getting ReplicaSetNoPrimary and MongoServerSelectionError error while connecting MongoDB with nodejs

I am trying to connect to mongodb but getting below error could you please help
var mongo = require('mongodb').MongoClient;
mongo.connect('mongodb://usernamexyz:passwordxyz#hostmxy-mw-e6-u1238.nam.nsroot.net:47017/sampleDB?replicaSet=NAME_2436&readPreference=primary&authSource=admin&w=1', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log("Mongodb connected"))
.catch(err => console.log(err));
And the error i am getting as below
MongoServerSelectionError: connection <monitor> to 155.30.360.129:37017 closed
at Timeout._onTimeout (C:\Fintech\NodeFirstApp\node_modules\mongodb\lib\core\sdam\topology.js:448: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 {
'hostmxy-mw-e6-u1238.nam.nsroot.net:47017' => [ServerDescription]
},
stale: false,
compatible: true,
compatibilityError: null,
logicalSessionTimeoutMinutes: null,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
commonWireVersion: null
},
[Symbol(mongoErrorContextSymbol)]: {}
}
Go to Mongodb where you created a cluster and under "ipwhitelist" click on the edit IP address button and then choose "Add current IP address"
There was a firewall issue for me, and here are the steps i followed:
Search for Windows Firewall with Advanced Security
Select Outbound Rules
Select New Rule
Select Port in Rule Type, Click next
Select TCP and Specific remote ports and write in there 27015-27017
Save the rule
This worked for me :)
I setup replica set on mongod server in order to have oplog facility and use it to sync database programmatically with golang client.
It was working fine with local windows server.
mongod.exe --dbpath $dpath --bind_ip 0.0.0.0 --port $port --replSet rs0
mongo.exe' -port $port --eval 'rs.initiate()'
When I used docker it showed me that ReplicaSetNoPrimary Error.
docker run --name mongo21 -d -p 27021:27017 mongo --bind_ip_all --replSet rs0
docker container exec mongo21 mongosh --eval 'rs.initiate()' 127.0.0.1
I noticed that perl client as well as Robo3 T, mongosh connected to the server localhost:27021 without problem.
mongosh shows which mongo uri it uses:
mongodb://127.0.0.1:27017/test?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.1.9
I found I can specify client option before connect:
clientOpts := options.Client().ApplyURI(uri).SetDirect(true)
client, err := mongo.Connect(ctx, clientOpts)
That option fixed golang client connection issue.
Some MongoDB implementations as a service such as IBM Cloud, GCP or AWS might need a certificate to be able to connect. That was my case. The problem was resolved when I added a certificate to the docker file and then passed the parameters as options
let options = {
tls: true,
tlsCAFile: `/path/to/cert`,
useUnifiedTopology: true
};
// connects to a MongoDB database
MongoClient.connect(connectionString, options)
Reference https://cloud.ibm.com/docs/databases-for-mongodb?topic=databases-for-mongodb-mongodb-external-app
I was also getting the same error while connecting to MongoDB atlas.
You have to do following things.
1. allow outbound port 27015-27017 in firewall in your system.
2. update the latest MongoDB and NodeJs.
3. whitelist your system IP in MongoDB atlas cluster under network access.
It worked for me. I hope it works for you also.
Updating "Network Access" did not work for me. What worked for me was to update "Database Access" by "Autogenerate Secure Password" and make sure to click "Update User" to save new password!
MongoDB Atlas > Database Access > complete 3 steps in image
I had the same issue with this. It was fixed when I added the current IP address to IP whitelist inside of MongoDB.
I was using Atlas Mongo Cluster and using 'mongomirror' I am trying to push the data from one replicaset cluster to another. In the process, I was getting this error..
After ot of research, I understood that, the name of cluster visible in UI should not be used.. instead you need to run the below command
rs.status()
This will give a JSON output which has the RS name and respective primary and secondary node endpoints you need to use.
In my case, for abc-temp-shard-cluster, the cluster name I got by running the above command was something like below
atlas-12avca-shard-0/atlas-12avca-shard-00-00.1aqer5.mongodb.net:27017,atlas-12avca-shard-00-01.1aqer5.mongodb.net:27017,atlas-12avca-shard-00-02.1aqer5.mongodb.net:27017
try to enable ipv6 support at mongo server using --ipv6 flag
mongod --dbpath="D:/data_path" -replSet rs0 --bind_ip 0.0.0.0,127.0.0.1,localhost,::1 --ipv6

Can't establish SSL connection to MongoDB from NodeJS program

I am trying to connect a mongod instance from NodeJS program using Mongoose that configured with SSL connection but I'm getting the following error on the mongod console: "Error receiving request from client: SSLHandshakeFailed: The server is configured to only allow SSL connections."
The mongod instance is initiated as follow:
mongod --sslMode requireSSL --sslPEMKeyFile C:/Users/MyUsername/Path/mongodb.pem
I tried to use MongoClient instead of mongoose but nothing new happened.
This is my piece of code:
if(envConfig.config.db.tls === true){
let certFile = [fs.readFileSync("C:/PATH/TO/Key/mongoDB.pem")];
mongoose.connect("mongodb://localhost:27017/DB_NAME?ssl=true",{
server:{
sslValidate: true,
sslCA: certFile
}
});
}else{
mongoose.connect(`mongodb://${dbUrl}`,options);
}
It is not something about the PEM file because when I start the mongod as I wrote and use SSL connection with MongoDB Compass using the same PEM file from the code - it works.
MongoDB version: 3.6.0
Mongoose version: 4.13.6
Happy if someone will guide me what am I doing wrong.
I think you should refer to the question Mongoose SSL, connection not accepted
You should specify {server: {ssl: true} parameter and I think your problem will be solved
If you initiate MongoDB daemon with private key and certificate
mongod --sslMode requireSSL --sslPEMKeyFile C:/Users/MyUsername/Path/mongodb.pem --sslCAFile C:/Users/MyUsername/Path/mongodb.crt
You can connect from Node JS like
if(envConfig.config.db.tls === true){
let key = fs.readFileSync("C:/Users/MyUsername/Path/mongodb.pem");
let crt = fs.readFileSync("C:/Users/MyUsername/Path/mongodb.crt");
mongoose.connect("mongodb://localhost:27017/DB_NAME?ssl=true",{
server:{
"sslValidate" :true
"sslKey": key,
"sslCert": crt, // if you have one certificate you can use `sslCert` parameter
}
});
}else{
mongoose.connect(`mongodb://${dbUrl}`,options);
}
More detail explanation of SSL connection via Node JS you can go here
Solved!
Problem was using express-session middelware and trying to connect the DB with incorrect connection string, that what caused the problem.

Node postgres ECONNREFUSED in localhost

This issue is totally driving me insane. I spent months with this, trying to make a SIMPLE NODE APP WORK. I finally managed to make an APP work in a nice server (Heroku) and with mysql. Problem? The server only accepts postgres. And this is my nightmare. I just cannot make it work. Searched dozens of webs and problems, all of them with the same error log as me... but I just cannot figure what to do. I'm totally idiot at configuring things, I cannot even start programming my app.
Error: connect ECONNREFUSED 127.0.0.1:5432
at Object._errnoException (util.js:1022:11)
at _exceptionWithHostPort (util.js:1044:20)
at TCPConnectWrap.afteeConnect [as oncomplete] (net.js:1198:14)
My start of server.js
const pg = require('pg');
const connectionString = process.env.DATABASE_URL || 'postgres://myrole:12345#localhost:5432/mydb';
And here the error.
var pool = new pg.Pool();
pool.connect().then(client => {
It crashes right at connection.
I did everything I searched for. I created "myrole" login role with all permission, password "12345", to connect to "mydb" database. I opened "pgAdmin4" application. Connected to "PostgreSQL 10" and "mydb". I saw that the first one connects to port 3000. I tried port 3000 in the connection string. I searched for the service at Windows. It's running. I JUST DID EVERYTHING and nothing works... I installed and made MySQL database to run in local in just 2 hours. But Heroku doesn't accept MySQL and I don't want to put any credit card. What's happening here?
I was having the same issue and I'll put my situation here and hopefully help someone else.
I was testing some AWS Lambda functions and since the code runs in a container and the container has its own localhost so my postgres connection was failing because there is no postgres server running on the container. Remember that your machine's localhost is not the same as the container's one, if your app is running inside a container the instead of localhost use your machine IP.
in your case, you shuld include connectionString inside new Pool() as property of Object
var pool = new pg.Pool({connectionString}); pool.connect().then()
or here is a more detailed version
let c = {
host: 'localhost',
port: 5432,
user: 'user',
password: 'password',
database: 'mydb',
options: `application_name=${app}&application_cmd=${cmd}`
};
const connection_string = {connectionString : `postgresql://${c.user}:${c.password}#${c.host}:${c.port}/${c.database}?${c.options}`};
const pool = new Pool(connection_string);
more details can be found here node-postgres.com

Connection to MongoDb failed

I was trying to connect my mongodb with node server using command prompt.
I started mongodb my mongod --dbpath E:\node start\node\data
Then I installed mongodb dependencies using npm install mongodb
I added some code into my app.js which is described below :
app.js
var mongodb = require('mongodb'); //acquiring mongodb native drivers
var mongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:7000/myDatabase'; //connection url
mongoClient.connect(url, function(err,db){
if(err){
console.log('Unable to connect to mongodb server. Error :' , err);
}
else{
console.log('Connection established to', url);
db.close();
}
});
when I ran app.js in command prompt, following error occured :
Unable to connect to mongodb server. Error :{[ MongoError : connect ECONNREFUSED] name : 'MongoError' , message: 'connect ECONNREFUSED' }
I cannot understand what the problem is and what should I do next.
MongoDB usually runs on port 27017, but you're trying to connect to port 7000. Try changing your url variable.
var url = 'mongodb://localhost:27017/myDatabase';
You know mongoDB has their default port no 27017.
And You have written 7000.
So Try to Change port no to 27017.
ok !!!!!!!
The error says you do not have mongodb running. You should check if your mongodb is running or not. If its running then you should check on what port it is running on.
The default port for mongodb is 27017. If you have not configured your mongodb to run on port 7000 then changing var url = 'mongodb://localhost:7000/myDatabase'; to var url = 'mongodb://localhost:27017/myDatabase'; will work for you.

Resources