Cannot connect to mongodb with strapi - node.js

PS C:\Users\mihir\Desktop\node leraning\strapi_practice> npx create-strapi-app first
npx: installed 92 in 92.729s
Creating a new Strapi application at C:\Users\mihir\Desktop\node leraning\strapi_practice\first.
? Choose your installation type
? Choose your installation type Custom (manual settings)
? Choose your default database client
? Choose your default database client mongo
? Database name: learn
? Database name: learn
? Host: cluster_link {useNewUrlParser: true, useUnifiedTopology: true}
? Host: cluster_link {useNewUrlParser: true, useUnifiedTopology: true}
? +srv connection: (false) true
? +srv connection: true
? Port (It will be ignored if you enable +srv): (27017)
? Port (It will be ignored if you enable +srv): 27017
? Username: mihir
? Username: mihir
? Password: ****************
? Password: ****************
? Authentication database (Maybe "admin" or blank):
? Authentication database (Maybe "admin" or blank):
? Enable SSL connection: (y/N) y
? Enable SSL connection: Yes
⛔️ Connection test failed: EPERM: operation not permitted, lstat 'C:\Users\mihir\AppData\Local\Temp\strapiff50605eed47\node_modules\strapi-connector-mongoose\node_modules\.bin'
I wrote a command to create a new strapi app with custom settings.I answered the custom setting questions in above manner.When i choose database as mongo I also passed {useNewUrlParser: true, useUnifiedTopology: true}.But at last it is showing connection test failed.So i am unable to connect with my mongo.Please suggest some solution.

I think that You should start mongodb first then start with installation

Related

Connect to SQL Server via Hamachi VPN - SSMS works, Node doesn't

I can connect fine with SQL Server Management Studio, but not with Node.
I am using the mssql npm package.
Here's the node connection.
db: {
server: "123.456.789.255\\WEBSQL",
database: "db_name",
user: "user",
password: "pass"
}
I am getting a ETIMEOUT error.
ConnectionError: Failed to connect to 123.456.789.255\\WEBSQL in 15000ms
Can anyone point me to the right direction?
Adding this fixed the problem.
options: {
encrypt: false,
},

Circleci, SequelizeConnectionError: no pg_hba.conf entry for host

I am using circleci to run some tests involving the database. My server uses node and sequelize as the orm. Whenever, I run my tests I get the following error:
SequelizeConnectionError: no pg_hba.conf entry for host X, user X, database X, SSL off
How do I fix this error?
I found the solution. In my model index file, where I create the instance of Sequelize, I needed to add the following options:
const sequelize = new Sequelize(
database_url,
{
ssl = true,
dialectOptions = {
ssl: true,
},
},
);
This fixed the it. The key is to set both ssl options. The problem was Sequelize was not using ssl.

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.

Unable to connect to atlas mongo db from strapi

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

Resources