I have a mongo replica set cluster with a ssl server validation. How can i connect to this with mongoose?
const key = fs.readFileSync(<Path to file>);
mongoose.connect(dbConectionString, {
sslCA: key,
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
}).then((x) => {
console.log('connected');
}).catch((err) => {
console.log(err);
});
The File has no file ending and looks like this:
-----BEGIN CERTIFICATE-----
MrPXxLy9NPj8isOutrLD29IY2A0V4RlcIxS0L7sVOy0zD6pmzMMQMD/5ifuIX6bq
[16 more rows]
VF1talRQZJjwryXlXboCG4156MKpL201L2WWjk0rvPUZ
-----END CERTIFICATE-----
This works (MongoDB Compass)
Error Message with this setup
connection error: MongooseError [MongooseServerSelectionError]: connection <monitor> to <server-ip>:<server-port> closed
at new MongooseServerSelectionError (D:\git_repos\WirVsVirus\Coronahelfer-Hackathon\node_modules\mongoose\lib\error\serverSelection.js:22:11)
at NativeConnection.Connection.openUri (D:\git_repos\WirVsVirus\Coronahelfer-Hackathon\node_modules\mongoose\lib\connection.js:823:32)
at Mongoose.connect (D:\git_repos\WirVsVirus\Coronahelfer-Hackathon\node_modules\mongoose\lib\index.js:333:15)
at new DBConection (D:\git_repos\WirVsVirus\Coronahelfer-Hackathon\.build\src\config\db\connection.js:13:28)
at Server.dbConfig (D:\git_repos\WirVsVirus\Coronahelfer-Hackathon\.build\src\server.js:31:20)
at new Server (D:\git_repos\WirVsVirus\Coronahelfer-Hackathon\.build\src\server.js:18:14)
at Function.bootstrap (D:\git_repos\WirVsVirus\Coronahelfer-Hackathon\.build\src\server.js:24:16)
at Object.<anonymous> (D:\git_repos\WirVsVirus\Coronahelfer-Hackathon\.build\src\server.js:36:23)
at Module._compile (internal/modules/cjs/loader.js:1151:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1171:10)
at Module.load (internal/modules/cjs/loader.js:1000:32)
at Function.Module._load (internal/modules/cjs/loader.js:899:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47 {
message: 'connection <monitor> to <server-ip>:<server-port> closed',
name: 'MongooseServerSelectionError',
reason: TopologyDescription {
type: 'Single',
setName: null,
maxSetVersion: null,
maxElectionId: null,
servers: Map(1) {
'<server-ip>:<server-port>' => [ServerDescription]
},
stale: false,
compatible: true,
compatibilityError: null,
logicalSessionTimeoutMinutes: null,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
commonWireVersion: null
},
[Symbol(mongoErrorContextSymbol)]: {}
}
Found a solution. add ssl=true to your connection string
this.DB_URL = 'mongodb://user:password#ip:port/collection?authSource=admin&ssl=true';
Related
I'm connecting mongodb with node js and getting such error
MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
at Connection.openUri (C:\Users\Dell\OneDrive\Desktop\New folder\node_modules\mongoose\lib\connection.js:825:32)
at C:\Users\Dell\OneDrive\Desktop\New folder\node_modules\mongoose\lib\index.js:419:10
at C:\Users\Dell\OneDrive\Desktop\New folder\node_modules\mongoose\lib\helpers\promiseOrCallback.js:41:5
at new Promise (<anonymous>)
at promiseOrCallback (C:\Users\Dell\OneDrive\Desktop\New folder\node_modules\mongoose\lib\helpers\promiseOrCallback.js:40:10)
at Mongoose._promiseOrCallback (C:\Users\Dell\OneDrive\Desktop\New folder\node_modules\mongoose\lib\index.js:1272:10)
at Mongoose.connect (C:\Users\Dell\OneDrive\Desktop\New folder\node_modules\mongoose\lib\index.js:418:20)
at connect_db (C:\Users\Dell\OneDrive\Desktop\New folder\db.js:5:36)
at Object.<anonymous> (C:\Users\Dell\OneDrive\Desktop\New folder\app.js:7:1)
at Module._compile (node:internal/modules/cjs/loader:1159:14) {
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
}
Here is my node.js code i am trying to connect aws document db using mongoose but getting
below error.
const URL = "mongodb://school:SJDJDJDJDD#dev-docdb-2022-09-02-05-55-49.cqsssmioaafcdjkaooj9.ap-south-1.docdb.amazonaws.com:27017/school?ssl=true&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false";
// Connect to MongoDB.
const connect = mongoose.connect(
URL, {
ssl: true,
sslValidate: true,
sslCA: `./rds-combined-ca-bundle.pem`,
useNewUrlParser: true,
useUnifiedTopology: true,
},
{}
);
errors i am getting
ubuntu#ip-172-31-38-108:~/school_api$ npm start
> graphql-crud#1.0.0 start
> node server.js
🚀 Server ready at http://localhost:4000/graphql
MongooseServerSelectionError: unable to get local issuer certificate
at Connection.openUri (/home/ubuntu/school_api/node_modules/mongoose/lib/connection.js:847:32)
at /home/ubuntu/school_api/node_modules/mongoose/lib/index.js:351:10
at /home/ubuntu/school_api/node_modules/mongoose/lib/helpers/promiseOrCallback.js:32:5
at new Promise (<anonymous>)
at promiseOrCallback (/home/ubuntu/school_api/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:10)
at Mongoose._promiseOrCallback (/home/ubuntu/school_api/node_modules/mongoose/lib/index.js:1149:10)
at Mongoose.connect (/home/ubuntu/school_api/node_modules/mongoose/lib/index.js:350:20)
at Object.<anonymous> (/home/ubuntu/school_api/server.js:18:26)
at Module._compile (node:internal/modules/cjs/loader:1119:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1173:10)
at Module.load (node:internal/modules/cjs/loader:997:32)
at Module._load (node:internal/modules/cjs/loader:838:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:18:47 {
reason: TopologyDescription {
type: 'ReplicaSetNoPrimary',
setName: null,
maxSetVersion: null,
maxElectionId: null,
servers: Map(1) {
'dev-docdb-2022-09-02-05-55-49.cqioaafcooj9.ap-south-1.docdb.amazonaws.com:27017' => [ServerDescription]
},
stale: false,
compatible: true,
compatibilityError: null,
logicalSessionTimeoutMinutes: null,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
commonWireVersion: null
}
}
I have my cerificate available also inside my code. please take a look.
I am able to connect to mongodb shell from the server. So there must be something wrong
in the code.
const URL = `mongodb://school:SJDJDJDJDD#dev-docdb-2022-09-02-05-55-49.cqsssmioaafcdjkaooj9.ap-south-1.docdb.amazonaws.com:27017/school?replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false`
const addedToUrl = `&tls=true&tlsCAFile=rds-combined-ca-bundle.pem`;
const connect = mongoose.connect(
`${URL}${addedToUrl}`, {
useNewUrlParser: true,
useUnifiedTopology: true,
},
{}
);
You can place these parameters in the connection string.
Hi I tried every thing like mongoose.connect('mongodb://localhost/blog') but I am not able to connect mongoose to node here is my code....
const express = require('express')
const mongoose = require('mongoose')
const articleRouter = require('./routes/articles')
const app = express()
mongoose.connect('mongodb://localhost:27017/blog')
app.set('view engine','ejs')
Here is the error:
/home/vishwajeet/webdeve/MARKDOWN-BLOG/node_modules/mongoose/lib/connection.js:807
const serverSelectionError = new ServerSelectionError();
^
MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
at NativeConnection.Connection.openUri (/home/vishwajeet/webdeve/MARKDOWN-BLOG/node_modules/mongoose/lib/connection.js:807:32)
at /home/vishwajeet/webdeve/MARKDOWN-BLOG/node_modules/mongoose/lib/index.js:342:10
at /home/vishwajeet/webdeve/MARKDOWN-BLOG/node_modules/mongoose/lib/helpers/promiseOrCallback.js:32:5
at new Promise (<anonymous>)
at promiseOrCallback (/home/vishwajeet/webdeve/MARKDOWN-BLOG/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:10)
at Mongoose._promiseOrCallback (/home/vishwajeet/webdeve/MARKDOWN-BLOG/node_modules/mongoose/lib/index.js:1181:10)
at Mongoose.connect (/home/vishwajeet/webdeve/MARKDOWN-BLOG/node_modules/mongoose/lib/index.js:341:20)
at Object.<anonymous> (/home/vishwajeet/webdeve/MARKDOWN-BLOG/server.js:8:10)
at Module._compile (node:internal/modules/cjs/loader:1103:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1157:10) {
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: 774709,
lastWriteDate: 0,
error: MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017
at connectionFailureError (/home/vishwajeet/webdeve/MARKDOWN-BLOG/node_modules/mongodb/lib/cmap/connect.js:375:20)
at Socket.<anonymous> (/home/vishwajeet/webdeve/MARKDOWN-BLOG/node_modules/mongodb/lib/cmap/connect.js:295:22)
at Object.onceWrapper (node:events:646:26)
at Socket.emit (node:events:526:28)
at emitErrorNT (node:internal/streams/destroy:157:8)
at emitErrorCloseNT (node:internal/streams/destroy:122: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
}
Hey I think your problem is that you don't have mongodb installed on your computer.
Once you download it you can change
mongoose.connect('mongodb://localhost:27017/blog')
to
mongoose.connect('mongodb://127.0.0.1/blog')
if the problem is still there
Youtube video for mongodb install
I am working on setting up a very simple full stack web application that can handle users signing up and logging in. For this, I have employed mongoose as a local database to store my users information after signup. This was working for a long time, but I recently ran my app after a week away from it and this happened:
MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
at NativeConnection.Connection.openUri (/Users/hca/Desktop/fullstacksus/node_modules/mongoose/lib/connection.js:845:32)
at /Users/hca/Desktop/fullstacksus/node_modules/mongoose/lib/index.js:345:10
at /Users/hca/Desktop/fullstacksus/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:5
at new Promise (<anonymous>)
at promiseOrCallback (/Users/hca/Desktop/fullstacksus/node_modules/mongoose/lib/helpers/promiseOrCallback.js:30:10)
at Mongoose._promiseOrCallback (/Users/hca/Desktop/fullstacksus/node_modules/mongoose/lib/index.js:1135:10)
at Mongoose.connect (/Users/hca/Desktop/fullstacksus/node_modules/mongoose/lib/index.js:344:20)
at Object.<anonymous> (/Users/hca/Desktop/fullstacksus/server.js:26:10)
at Module._compile (node:internal/modules/cjs/loader:1102:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1131:10)
at Module.load (node:internal/modules/cjs/loader:967:32)
at Function.Module._load (node:internal/modules/cjs/loader:807:14)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)
at node:internal/main/run_main_module:17:47 {
reason: TopologyDescription {
type: 'Unknown',
setName: null,
maxSetVersion: null,
maxElectionId: null,
servers: Map(1) { 'localhost:27017' => [ServerDescription] },
stale: false,
compatible: true,
compatibilityError: null,
logicalSessionTimeoutMinutes: null,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
commonWireVersion: null
}
}
node:internal/process/promises:225
triggerUncaughtException(err, true /* fromPromise */);
^
MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
at NativeConnection.Connection.openUri (/Users/hca/Desktop/fullstacksus/node_modules/mongoose/lib/connection.js:845:32)
at /Users/hca/Desktop/fullstacksus/node_modules/mongoose/lib/index.js:345:10
at /Users/hca/Desktop/fullstacksus/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:5
at new Promise (<anonymous>)
at promiseOrCallback (/Users/hca/Desktop/fullstacksus/node_modules/mongoose/lib/helpers/promiseOrCallback.js:30:10)
at Mongoose._promiseOrCallback (/Users/hca/Desktop/fullstacksus/node_modules/mongoose/lib/index.js:1135:10)
at Mongoose.connect (/Users/hca/Desktop/fullstacksus/node_modules/mongoose/lib/index.js:344:20)
at Object.<anonymous> (/Users/hca/Desktop/fullstacksus/server.js:26:10)
at Module._compile (node:internal/modules/cjs/loader:1102:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1131:10)
at Module.load (node:internal/modules/cjs/loader:967:32)
at Function.Module._load (node:internal/modules/cjs/loader:807:14)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)
at node:internal/main/run_main_module:17:47 {
reason: TopologyDescription {
type: 'Unknown',
setName: null,
maxSetVersion: null,
maxElectionId: null,
servers: Map(1) {
'localhost:27017' => ServerDescription {
address: 'localhost:27017',
error: Error: connect ECONNREFUSED 127.0.0.1:27017
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1133:16) {
name: 'MongoNetworkError'
},
roundTripTime: -1,
lastUpdateTime: 57762916,
lastWriteDate: null,
opTime: null,
type: 'Unknown',
topologyVersion: undefined,
minWireVersion: 0,
maxWireVersion: 0,
hosts: [],
passives: [],
arbiters: [],
tags: []
}
},
stale: false,
compatible: true,
compatibilityError: null,
logicalSessionTimeoutMinutes: null,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
commonWireVersion: null
}
}
[nodemon] app crashed - waiting for file changes before starting...
For reference, this is a very stripped down version of my server.js file:
if (process.env.NODE_ENV !== "production") {
require('dotenv').config({ path: '.env' });
}
const express = require('express');
const mongoose = require('mongoose');
const app = express();
mongoose.connect(process.env.MONGO_URL, { useNewUrlParser: true, useUnifiedTopology: true, 'useCreateIndex': true });
mongoose.connection.on('error', error => console.log(error));
mongoose.connection.once('open', () => console.log("Connected To Database"));
const indexRouter = require('./routes/index');
app.use('/', indexRouter);
app.listen(3030);
and this is my .env file:
MONGO_URL=mongodb://localhost/fullstacksus
very simple, and, as of a week ago working perfectly.
I think you have to run the MongoDB server as well before starting the project.
you may use any of the following, (Supposedly, you already have installed the mongodb in your system).
I will suggest you to install the mongodb community edition from the following link
https://docs.mongodb.com/manual/administration/install-community/
Then after installing it.
Just start the service in a terminal by the command
Ubuntu
sudo systemctl start mongod
Windows
After setting the environment variable path to mongod.exe run the following command in the terminal.
mongod
I've connected my app with Mongo DB database but when running my app I'm getting this error below,also I confirmed that my username and password are correct, I've seen some questions here like this before but nothing helped me, any help or guidance?
[nodemon] starting `node app.js`
MongooseServerSelectionError: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted. Make sure your current IP address is on your Atlas cluster's IP whitelist: https://docs.atlas.mongodb.com/security-whitelist/
at NativeConnection.Connection.openUri (C:\Users\user\Desktop\my port\node_modules\mongoose\lib\connection.js:800:32)
at Mongoose.connect (C:\Users\user\Desktop\my port\node_modules\mongoose\lib\index.js:339:15)
at Object.<anonymous> (C:\Users\user\Desktop\my port\app.js:7:10)
at Module._compile (internal/modules/cjs/loader.js:1251:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1272:10)
at Module.load (internal/modules/cjs/loader.js:1100:32)
at Function.Module._load (internal/modules/cjs/loader.js:962:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47 {
reason: TopologyDescription {
type: 'ReplicaSetNoPrimary',
setName: null,
maxSetVersion: null,
maxElectionId: null,
servers: Map(3) {
'codie-shard-00-00.lcuzy.mongodb.net:27017' => [ServerDescription],
'codie-shard-00-01.lcuzy.mongodb.net:27017' => [ServerDescription],
'codie-shard-00-02.lcuzy.mongodb.net:27017' => [ServerDescription]
},
stale: false,
compatible: true,
compatibilityError: null,
logicalSessionTimeoutMinutes: null,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
commonWireVersion: null
}
}
Seems you have not whitelisted your IP address on MongoDB Atlas cluster,
follow below and whitelist
https://docs.atlas.mongodb.com/tutorial/whitelist-connection-ip-address/