Cannot Connect to a MongoDB using Node.js and Mongoose - node.js

I am trying to connect my node app to a mongoDB atlas DB.
I have followed all the steps i usually follow but for some reason it just wont connect.
My code is as below (it usually uses a .env file to store the connection string but i have simplified into a variable for testing purposes)
const mongoose = require('mongoose');
//Connect to Mongoose DB
const URI = "mongodb+srv://AdminUser:**PASSWORD**#cluster0.l0f31.mongodb.net/omegadb?retryWrites=true&w=majority"
console.log("attempting to connect to MongoDB");
mongoose.connect(URI,{useNewUrlParser: true, useUnifiedTopology:true})
.then((result)=>console.log("Connected to db"))
.catch((err) => console.log(err))
This is giving me the below error in the console:
attempting to connect to MongoDB
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:\HTML\omega\node_modules\mongoose\lib\connection.js:824:32)
at C:\HTML\omega\node_modules\mongoose\lib\index.js:381:10
at C:\HTML\omega\node_modules\mongoose\lib\helpers\promiseOrCallback.js:41:5
at new Promise (<anonymous>)
at promiseOrCallback (C:\HTML\omega\node_modules\mongoose\lib\helpers\promiseOrCallback.js:40:10)
at Mongoose._promiseOrCallback (C:\HTML\omega\node_modules\mongoose\lib\index.js:1234:10)
at Mongoose.connect (C:\HTML\omega\node_modules\mongoose\lib\index.js:380:20)
at Object.<anonymous> (C:\HTML\omega\app.js:20:16)
at Module._compile (node:internal/modules/cjs/loader:1126:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10) {
reason: TopologyDescription {
type: 'ReplicaSetNoPrimary',
servers: Map(3) {
'cluster0-shard-00-00.l0f31.mongodb.net:27017' => [ServerDescription],
'cluster0-shard-00-01.l0f31.mongodb.net:27017' => [ServerDescription],
'cluster0-shard-00-02.l0f31.mongodb.net:27017' => [ServerDescription]
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
setName: 'atlas-4p8j1o-shard-0',
maxElectionId: null,
maxSetVersion: null,
commonWireVersion: 0,
logicalSessionTimeoutMinutes: null
},
code: undefined
}
I have checked the following, none of which seem to have helped:
My user name seems to be correct
My password is correct
The database name is correct in the connection string
I have checked that the network access in mongoDB is allowing my IP as it mentions this in the error, but it is (i actually set it to allow all IPs for testing purposes and still doesnt help)
Any ideas, i have been wracking my brain on it for hours?

Related

Should my mongoose.connect setup that works on a Mac work without being customised for Windows?

I had built a really simple API using Node and Express. It runs perfectly on my Mac, but when I cloned the repo from Github and tried to run it on a Windows laptop I get the following error message in the terminal.
MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
at NativeConnection.Connection.openUri (C:\Users\wande\Employee-Tracker\node_modules\mongoose\lib\connection.js:819:32)
at C:\Users\wande\Employee-Tracker\node_modules\mongoose\lib\index.js:379:10
at C:\Users\wande\Employee-Tracker\node_modules\mongoose\lib\helpers\promiseOrCallback.js:32:5
at new Promise ()
at promiseOrCallback (C:\Users\wande\Employee-Tracker\node_modules\mongoose\lib\helpers\promiseOrCallback.js:31:10)
at Mongoose._promiseOrCallback (C:\Users\wande\Employee-Tracker\node_modules\mongoose\lib\index.js:1224:10)
at Mongoose.connect (C:\Users\wande\Employee-Tracker\node_modules\mongoose\lib\index.js:378:20)
at Object. (C:\Users\wande\Employee-Tracker\index.js:12:10)
at Module._compile (node:internal/modules/cjs/loader:1105:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10) { reason:
TopologyDescription {
type: 'Unknown',
servers: Map(1) { 'localhost:27017' => [ServerDescription] },
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
logicalSessionTimeoutMinutes: undefined }, code: undefined }
My mongoose.connect setup in my index.js is as follows.
mongoose.connect('mongodb://localhost:27017/employeeData', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => {
console.log('MONGO CONNECTION OPEN');
})
.catch(err => {
console.log('MONGO CONNECTION ERROR');
console.log(err);
})
As I have said it seems to run perfectly on my Mac but I'm hitting major issues on a Windows laptop.
Does my mongoose.connect code need to be configured differently for it to run on Windows?
Many thanks
Rob

Could not connect to any servers in your MongoDB Atlas cluster

My mongodb local connection is successful but when i deploy to node server of sftp it gives mongodb network error,so please give me right answerand support.
while trying to connect with mongodb i’m getting this error :
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 (/root/Whatshapp/Chat/node_modules/mongoose/lib/connection.js:819:32)
at /root/Whatshapp/Chat/node_modules/mongoose/lib/index.js:379:10
at /root/Whatshapp/Chat/node_modules/mongoose/lib/helpers/promiseOrCallback.js:32:5
at new Promise (<anonymous>)
at promiseOrCallback (/root/Whatshapp/Chat/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:10)
at Mongoose._promiseOrCallback (/root/Whatshapp/Chat/node_modules/mongoose/lib/index.js:1224:10)
at Mongoose.connect (/root/Whatshapp/Chat/node_modules/mongoose/lib/index.js:378:20)
at Object.<anonymous> (/root/Whatshapp/Chat/db/db.js:4:21)
at Module._compile (internal/modules/cjs/loader.js:999:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10) {
reason: TopologyDescription {
type: 'ReplicaSetNoPrimary',
servers: Map {
'cluster0-shard-00-00.x1fjc.mongodb.net:27017' => [ServerDescription],
'cluster0-shard-00-01.x1fjc.mongodb.net:27017' => [ServerDescription],
'cluster0-shard-00-02.x1fjc.mongodb.net:27017' => [ServerDescription]
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
setName: 'atlas-j9ttqh-shard-0',
logicalSessionTimeoutMinutes: undefined
},
code: undefined
}
And mongodb network access is :

MongooseServerSelectionError: Could not connect to any servers in your MongoDB Atlas cluster

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.
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\Admin\Desktop\Working\SB\node_modules\mongoose\lib\connection.js:832:32)
at C:\Users\Admin\Desktop\Working\SB\node_modules\mongoose\lib\index.js:345:10
at C:\Users\Admin\Desktop\Working\SB\node_modules\mongoose\lib\helpers\promiseOrCallback.js:31:5
at new Promise (<anonymous>)
at promiseOrCallback (C:\Users\Admin\Desktop\Working\SB\node_modules\mongoose\lib\helpers\promiseOrCallback.js:30:10)
at Mongoose._promiseOrCallback (C:\Users\Admin\Desktop\Working\SB\node_modules\mongoose\lib\index.js:1135:10)
at Mongoose.connect (C:\Users\Admin\Desktop\Working\SB\node_modules\mongoose\lib\index.js:344:20)
at Object.<anonymous> (C:\Users\Admin\Desktop\Working\SB\app.js:305:10) at Module._compile (internal/modules/cjs/loader.js:1138:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
at Module.load (internal/modules/cjs/loader.js:986:32)
at Function.Module._load (internal/modules/cjs/loader.js:879:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47 {
reason: TopologyDescription {
type: 'ReplicaSetNoPrimary',
setName: null,
maxSetVersion: null,
maxElectionId: null,
servers: Map {
'smile-shard-00-00.xeyqd.mongodb.net:27017' => [ServerDescription],
'smile-shard-00-01.xeyqd.mongodb.net:27017' => [ServerDescription],
'smile-shard-00-02.xeyqd.mongodb.net:27017' => [ServerDescription]
},
stale: false,
compatible: true,
compatibilityError: null,
logicalSessionTimeoutMinutes: null,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
commonWireVersion: null
}
}
I have already update IP address to mongodb network access => IP Access list to 0.0.0.0/0
But the error has still occurred. I think this error is occurring due to the window firewall. But I have not any idea to resolve this.

Connection error between nodejs and mongodb atlas using mongoose

I am trying to build a backend app using mongodb atlas. I have followed the instruction but I got error like this
{ MongooseServerSelectionError: connect ECONNREFUSED 18.140.224.177:27017
at new MongooseServerSelectionError
...
message: 'connect ECONNREFUSED 18.140.224.177:27017',
name: 'MongooseServerSelectionError',
reason:
TopologyDescription {
type: 'ReplicaSetNoPrimary',
setName: null,
maxSetVersion: null,
maxElectionId: null,
servers:
Map {
'database-shard-00-01-ayo9w.mongodb.net:27017' => [ServerDescription],
'database-shard-00-00-ayo9w.mongodb.net:27017' => [ServerDescription],
'database-shard-00-02-ayo9w.mongodb.net:27017' => [ServerDescription]
stale: false,
compatible: true,
compatibilityError: null,
logicalSessionTimeoutMinutes: null,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
commonWireVersion: null },
[Symbol(mongoErrorContextSymbol)]: {} }
and here is my code
const mongoose = require('mongoose');
mongoose.connect("mongodb+srv://thanh:Abcdefghijk#database-ayo9w.mongodb.net/test?retryWrites=true&w=majority",
{ useNewUrlParser: true, useUnifiedTopology: true, },
).then(() => console.log('Connected to database')).
catch(err => console.log('Error in connection', err));
My whitelist entry in mongodb atlas is 0.0.0.0/0
Change username and password with your database username and password. Check mongoDB Atlas where you have created your database and collections.
The reason for this is the internet connection. I just change my wifi connection and it works. This is the link where I get the answer
Error at connecting to MongoDb Atlas Server
Your network or hosting has port 27017 blocked, that's why you can't access server.
To test if the port is blocked you can try this on terminal on mac/linux
(curl portquiz.net:27017) or on cmd (nc -v portquiz.net 27017)
This should solve your issue.

Connect NodeJS to MongoDB Droplet

So I've decided to set up my project with two droplets, a MongoDB image droplet and a NodeJS image droplet. I did so to make it easier to scale both droplets in the future, and other applications may be connecting to the DB in the future, both on Ubuntu 18.04.
I'm getting the error of:
Could not connect to the database: { MongooseServerSelectionError: connection timed out
at new MongooseServerSelectionError (/root/eternal-peace-code/node_modules/mongoose/lib/error/serverSelection.js:22:11)
at NativeConnection.Connection.openUri (/root/eternal-peace-code/node_modules/mongoose/lib/connection.js:808:32)
at Mongoose.connect (/root/eternal-peace-code/node_modules/mongoose/lib/index.js:333:15)
at Timeout.setTimeout [as _onTimeout] (/root/eternal-peace-code/app.js:60:22)
at ontimeout (timers.js:482:11)
at tryOnTimeout (timers.js:317:5)
at Timer.listOnTimeout (timers.js:277:5)
message: 'connection timed out',
name: 'MongooseServerSelectionError',
reason:
TopologyDescription {
type: 'Single',
setName: null,
maxSetVersion: null,
maxElectionId: null,
servers: Map { 'mongo_droplet_ip:27017' => [Object] },
stale: false,
compatible: true,
compatibilityError: null,
logicalSessionTimeoutMinutes: null,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
commonWireVersion: null },
[Symbol(mongoErrorContextSymbol)]: {} }
I have set up both servers correctly (so I believe), my MongoDB has two users (both are me but different permissions, I have followed several walkthroughs and so it just happened). My /etc/mongod.conf file has been edited accordingly:
net:
port: 27017
bindIp: 127.0.0.1,mongodb_droplet_ip
security:
authorization: "enabled"
The UFW firewall has HTTPS, SSH and my NodeJS_ip:27017 enabled.
My NodeJS droplet is set up with a domain name pointing to the right IP address, letsencrypt is set up for secure connection at the domain name. The issue I have now is that I can not connect to my Mongo droplet from my NodeJS application, and I would also like to make sure that it is all done securely too.
My NodeJS connect code is using Mongoose and a variables environment file, I also have the whole connect in a timeout function as per another suggestion I saw elsewhere:
setTimeout(async () => {
console.log('Connecting to database...');
const options = {
user: process.env.DBUSER,
pass: process.env.USERPASS,
keepAlive: true,
useNewUrlParser: true,
useFindAndModify: false,
useCreateIndex: true,
useUnifiedTopology: true,
sslCA: cert,
connectTimeoutMS: 5000,
}
await mongoose.connect(process.env.LIVEDB, options)
.then(() => {
console.log('We are connected to the database');
})
.catch(err => {
console.log('Could not connect to the database: ', err);
connectWithTimeout();
});
}, 3000);
I have tried a multitude of things through both droplets but I have wasted around 4 days on getting the project to a staging/production stage so it can launch whenever and just be updated as time goes on.
If you need anything else, please do let me know.
All help would be hugely appreciated,
Thanks
I don't know the URI format you are using. But I got the same issue initially when I tried to connect my node application with Mongo instance of AWS.
Using the long URI sting with all the cluster name like this
mongoURI = 'mongodb://username:password#mongo-instance-shard-00-00-a4iv8.mongodb.net:27017,mongo-instance-shard-00-01-a4iv8.mongodb.net:27017,mongo-instance-shard-00-02-a4iv8.mongodb.net:27017/test?ssl=true&replicaSet=mongo-instance-shard-0&authSource=admin&retryWrites=true&w=majority'
Instead of something like this:
mongodb+srv://server.example.com/
This worked for me. It might help you as well.
Also, found this for digital ocean link
and mongo documentation for the connection string

Resources