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
Related
I am using the free subscription at Azure and have successfully created a Ubuntu Server and a Flexible Postgres Database.
Until recently I accessed the DB directly from my Windows 10 desktop. Now I want to route all access through the Ubuntu Server.
For this I have installed Open SSH Client and Open SSH Server on my Windows 10 machine and done the necessary local port forwarding with ssh -L 12345:[DB IP]:5432 my_user#[Ubuntu IP]
The connection works, I confirmed it with pgcli on my desktop with pgcli -h 127.0.0.1 -p 12345 -u my_user -d my_db
But when I am trying to connect via node-pg I receive the following error
UnhandledPromiseRejectionWarning: error: no pg_hba.conf entry for host "[Ubuntu IP]", user "my_user", database "my_db", SSL off
I have already added a Firewall Rule in Azure with the [Ubuntu IP], and the error remains. What bugs me further is that in the Azure Portal of the DB I have enabled "Allow public access from any Azure service within Azure to this server", so the extra Firewall should not even be necessary for this connection.
For the last week, I have been stuck on this and now the connection is finally established, but not accessible by my code. Pretty frustrating. I would be glad about ANY pointers on how to fix this.
Edit #1:
I can't post the pg_hba.conf file. Because the Postgres DB is managed by Azure, I do not have access to pg_hba, which makes the situation more difficult to understand.
My node.js code for testing the connection:
const pg = require("pg");
const passwd = "...";
const client = new pg.Client({
user: 'admin',
host: '127.0.0.1',
database: 'test',
password: passwd,
port: 12345
});
client.connect()
client.on('uncaughtException', function (err) {
console.error(err.stack);
});
const query = "SELECT * FROM test";
try {client.query(query, (err,res) => {
if (err) {
console.error(err);
}
console.log(res);
})}
catch (e) {
console.error(e)
}
The comment by #jjanes helped me in understanding the issue, thank you.
This edited pg.Client config solved my problem:
const client = new pg.Client({
user: 'admin',
host: '127.0.0.1',
database: 'test',
password: passwd,
port: 12345,
ssl: {rejectUnauthorized: false}
});
I found this specific SSL option here https://node-postgres.com/features/ssl
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.
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.
I am using strapi and Mongo DB.
Am able to connect to mlab Mongo DB, but not to atlas clustered Mongo DB.
I am using following configuration in strapi config :
{
"defaultConnection": "default",
{
"connections": {
"default": {
"connector": "strapi-mongoose",
"settings": {
"client": "mongo",
"uri": "mongodb://<username>:<pwd>#mydb-shard-00-00-abcde.mongodb.net:27017,my-db-shard-00-01-abcde.mongodb.net:27017,mydb-shard-00-02-abcde.mongodb.net:27017/mydb?ssl=true&replicaSet=mydb-shard-0&authSource=admin",
},
"options": {"ssl":true}
}
}
}
Updated
It is working as expected there was mismatch in the spelling of clusters. For one of the clusters there is capital letter.
If you just start with new project you just need to do run
yarn create strapi-app my-strapi
then Choose your installation type
Custom (manual settings)Choose your installation type Custom (manual
settings)
Choose your main database:
SQLite
❯ Mongo
MySQL
Postgres
Database name: (my-strapi) (shows project name by default; hit enter)
Host: myproject-fcvyt.mongodb.net
+srv connection: true
Port (It will be ignored if you enable +srv): 27017 (do nothing, simply hit enter)
Username:<mongodb atlas cluster username>
Password:<mongodb atlas cluster password>
Authentication database (Maybe "admin" or blank): (leave blank hit enter)
Enable SSL connection: true
MongoDB atlas uri should include +srv. E.g., "mongodb+srv://<username>:<pwd>..."
*this is assuming you are using the node.js driver and MongoDB 3.6. Full doc here.
for reference these are the options that worked for me
Choose your default database client mongo
? Database name: server
? Host: cluster0.qcyvc.mongodb.net
? +srv connection: true
? Port (It will be ignored if you enable +srv): 27017
? Username: petros
? Password: ********
? Authentication database (Maybe "admin" or blank):
? Enable SSL connection: Yes
have been trying to connect my docker node.js app to a mongodb service to no avail.
I've created a was liberty bridging application ($BRIDGE_APP) with no war or code that is bound to a mongodb service. It is running with good status.
Have to say that the same code is running correctly in my local docker container. I am using mongoose to connect to mongo.The only difference in the code is the way of resolving the mongo connection string:
var DB_CONNECT_STRING = 'mongodb://app:password#127.0.0.1:27017/appname';
if(custom.areWeOnBluemix() && custom.doWeHaveServices())
DB_CONNECT_STRING = custom.getMongoConnectString();
...
console.log('going to connect to mongo#: ' + DB_CONNECT_STRING);
var db = mongoose.createConnection(DB_CONNECT_STRING);
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
console.log('... db open !!!');
});
I push my image to bluemix with no issues:
ice --local push $REGISTRY/$ORG/$CONTAINER_NAME
I then check the env vars:
cf env $BRIDGE_APP
System-Provided:
{
"VCAP_SERVICES": {
"mongodb-2.4": [
{
"credentials": {.....
and then I run my container and bind an ip:
ice run --bind $BRIDGE_APP --name $CONTAINER_NAME -p $PORT $REGISTRY/$ORG/$CONTAINER_NAME:latest
sleep 12
ice ip bind $IP $CONTAINER_NAME
...this is almost completely by the book, but for some reason when I check the logs I'm always getting:
ice logs $CONTAINER_NAME
...
going to connect to mongo#: mongodb://c61deb58-45ea-41....
Example app listening at http://0.0.0.0:8080
connection error: { [MongoError: connect ENETUNREACH] name: 'MongoError', message: 'connect ENETUNREACH' }
I have also tried with mongolab service with no success.
Has anybody somehow eventually tried this type of setup that can provide me some additional clue of what's missing here?
thanking you in advance
It has been my experience that networking is not reliable in IBM Containers for about 5 seconds at startup. Try adding a "sleep 10" to your CMD or ENTRYPOINT. Or set it up to retry for X seconds before giving up.
Once the networking comes up it has been reliable for me. But the first few seconds of a containers life have had troubles with DNS, binding, and outgoing traffic.
I gave a similar answer to a similar question recently. Perhaps your problem is the same as the other poster's.