Unable to connect to Mongodb Atlas using mongoose - mongodb

I am trying to connect to a cluster created in Mongodb Atlas using mongoose in node js and I am facing below issues when doing so.
When I use the connection string that is given in the Mongo db atlasmongodb+srv://lm_dev_app:<password>#lmdev-q5biw.mongodb.net/test?retryWrites=true&w=majorityI get below error
{ Error: queryTxt EBADNAME lmdev-q5biw.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (dns.js:196:19)
errno: 'EBADNAME',
code: 'EBADNAME',
syscall: 'queryTxt',
hostname: 'lmdev-q5biw.mongodb.net'}
I cannot use this connection string in Mongodb Compass as well as I am getting the same error there.
If I try to connect using mongodb://lm_dev_app:<password>#lmdev-shard-00-01-q5biw.mongodb.net/test i get below error
MongooseServerSelectionError: connection to 54.66.221.230:27017 closed
However I am able to connect to each node using Mongodb Compass which eliminates the possibility of my ipaddress not being whitelisted.
Here is the sample code that I am using
const mongoosePromise = mongoose.connect("mongodb://lm_dev_app:<password>#lmdev-shard-00-01-q5biw.mongodb.net/test", {
useNewUrlParser: true,
useUnifiedTopology: true,
replicaSet: "LMDEV"
}, (err) => {
if (err) {
console.log(err);
} else {
console.log("Successful");
}
});
Any thoughts on what is happening here.

There are couple of things that I need to highlight here.
The default connection string that is shown in Mongodb Atlas seems to be wrong. It shows you mongodb+srv://<username>:<password>#<cluster_url>/test?retryWrites=true&w=majority. But I used mongodb://<username>:<password>#<node_url>:27017/ to make it work. You can also use mongodb://<username>:<password>#<node_url>:27017/admin.
Pass ssl:true in the options that we are passing.
Finally one of the 3 options can be used to connect to the database.
a. const mongoosePromise = mongoose.connect("mongodb://lm_dev_app:<password>#lmdev-shard-00-01-q5biw.mongodb.net:27017/", {
useNewUrlParser: true,
useUnifiedTopology: true,
authSource:"admin",
ssl: true,
}, (err) => {
if (err) {
console.log(err);
} else {
console.log("Successful");
}
});
b. const mongoosePromise = mongoose.connect("mongodb://lm_dev_app:<password>#lmdev-shard-00-01-q5biw.mongodb.net:27017/", {
useNewUrlParser: true,
useUnifiedTopology: true,
authSource:"admin",
ssl: true,
}, (err) => {
if (err) {
console.log(err);
} else {
console.log("Successful");
}
});
c. const mongoosePromise = mongoose.connect("mongodb://lm_dev_app:<password>#lmdev-shard-00-01-q5biw.mongodb.net:27017/admin", {
useNewUrlParser: true,
useUnifiedTopology: true,
ssl: true,
}, (err) => {
if (err) {
console.log(err);
} else {
console.log("Successful");
}
});
EDIT 1:
After having a chat with Atlas support team I was told that issue in point 1 is due to DNS resolution issue with my service provider. So i have changed my DNS settings to point to a public DNS server.

After trying different connection strings for several hours, I finally just copy/pasted the connection string from MongoDB Compass and it works! (first connect, then edit the connection string as it will change)
It looks like this:
mongodb+srv://username:password#fra-atlas-shard.abcde.mongodb.net/test?authSource=admin&replicaSet=atlas-abcde-shard-0&readPreference=primary&appname=MongoDB%20Compass&ssl=true

Related

Could not connect to any servers in your MongoDB Atlas cluster. I have already allowed access from anywhere but the issue isn't resolved

I keep getting this error although I have allowed access from anywhere in the Network access section of the cluster. (Screenshot of the same is attached below)
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 (/home/runner/store-cipher-backend-1/node_modules/mongoose/lib/connection.js:824:32)
at /home/runner/store-cipher-backend-1/node_modules/mongoose/lib/index.js:380:10
at /home/runner/store-cipher-backend-1/node_modules/mongoose/lib/helpers/promiseOrCallback.js:32:5
at new Promise (<anonymous>)
at promiseOrCallback (/home/runner/store-cipher-backend-1/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:10)
at Mongoose._promiseOrCallback (/home/runner/store-cipher-backend-1/node_modules/mongoose/lib/index.js:1225:10)
at Mongoose.connect (/home/runner/store-cipher-backend-1/node_modules/mongoose/lib/index.js:379:20)
at intialDbConnection (/home/runner/store-cipher-backend-1/db/db.connect.js:5:20)
at Object.<anonymous> (/home/runner/store-cipher-backend-1/index.js:15:1) {
reason: TopologyDescription {
type: 'ReplicaSetNoPrimary',
servers: Map(3) {
'cluster0-shard-00-00.fkvic.mongodb.net:27017' => [ServerDescription],
'cluster0-shard-00-01.fkvic.mongodb.net:27017' => [ServerDescription],
'cluster0-shard-00-02.fkvic.mongodb.net:27017' => [ServerDescription]
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
setName: 'atlas-on2j4f-shard-0',
logicalSessionTimeoutMinutes: undefined
},
code: undefined
}
Here is the connection code
const mongoose = require('mongoose');
const mySecret = process.env['mongoUrl']
const intialDbConnection = async () => {
try {
await mongoose.connect(mySecret, {
useNewUrlParser: true,
useUnifiedTopology: true
})
console.log("db connected")
}
catch (error) {
console.error(error);
}
}
module.exports = { intialDbConnection }
And the entire code is here https://replit.com/#KumaraswamyA/store-cipher-backend-1
Access from anywhere mongodb access management
If you are looking for an answer follow this thread. mongoDB community support
The MongoDB community has made it clear that the error is not from their end.
and after reaching out to Replit. They responded that they are aware of the issue and have provided a temporary solution:
“You can run “kill 1” in the shell of your Repl which will reboot it and may fix the issue, although it isn’t a 100% reliable workaround.”
Apart from this the solution that has worked for me is changing the file name and running, the DB gets connected. In case you have already used the APIs in the frontend, after doing the above step change back your file name to the old one and the DB gets connected without any issues.
Cheers.

Connection between MongoDB Atlas and AWS giving timeout error?

I'm new to AWS so I apologize for any newbie stuff.
I'm trying to connect a MongoDB Atlas M0 cluster with our AWS EC2 instance, which is running a nodejs / react stack. The problem is that I can't make these two instances connect - AWS and MongoDB that is. When trying to use the backend sign in function (our nodejs api), it just gives this error:
Operation `user_profile.findOne()` buffering timed out after 10000ms
This is our index / connection:
import config from './config';
import app from './app';
import { connect } from 'mongoose'; // MongoDB
import { ServerApiVersion } from 'mongodb';
import https from 'https';
import AWS from 'aws-sdk';
const makeLogger = (bucket: string) => {
const s3 = new AWS.S3({
accessKeyId: <ACCESS_KEY_ID>,
secretAccessKey: <SECRET_ACCESS_KEY>
});
return (logData: any, filename: string) => {
s3.upload({
Bucket: bucket, // pass your bucket name
Key: filename, // file will be saved as testBucket/contacts.csv
Body: JSON.stringify(logData, null, 2)
}, function (s3Err: any, data: any) {
if (s3Err) throw s3Err
console.log(`File uploaded successfully at ${data.Location}`)
});
console.log(`log (${filename}): ${logData}`);
};
};
const log = makeLogger('xxx-xxxx');
log(config.MONGO_DB_ADDRESS, 'mongo_db_address.txt');
const credentials = <CREDENTIALS>
connect(config.MONGO_DB_ADDRESS, {
sslKey: credentials,
sslCert: credentials,
serverApi: ServerApiVersion.v1
}) //, { useNewUrlParser: true })
.then(() => console.log('Connected to MongoDB'))
.catch((err) => console.error('Failed connection to MongoDB', err));
app.on('error', error => {
console.error('app error: ' + error);
});
app.listen(config.WEB_PORT, () => {
console.log(`Example app listening on port ${config.WEB_PORT}`);
});
One of the endpoints giving the timeout error:
router.post('/signin', async (req, res) => {
var form_validation = signin_schema.validate({
email: req.body.email,
password: req.body.password,
});
if (form_validation.error) {
console.log('form validation sent');
//return res.status(400).send(form_validation);
return res.status(400).send({
kind: 'ERROR',
message: 'Sorry - something didn\'t go well. Please try again.'
});
}
var User = model('model', UserSchema, 'user_profile');
User.findOne({ email: req.body.email }, (err: any, the_user: any) => {
if (err) {
return res.status(400).send({
kind: 'ERROR',
message: err.message
});
}
if (!the_user) {
return res.status(400).send({
kind: 'ERROR',
message: 'the_user undefined',
});
}
compare(req.body.password, the_user.password)
.then((result) => {
if (result == true) {
const user_payload = { name: the_user.name, email: the_user.email };
const access_token = sign(user_payload, config.SECRET_TOKEN);
res.cookie('authorization', access_token, {
httpOnly: true,
secure: false,
maxAge: 3600000,
});
return res.send({ kind: "LOADING" });
// return res.send(access_token);
} else {
return res.status(400).send({
kind: 'ERROR',
message: 'Sorry - wrong password or email used.'
});
}
})
})
});
The strange thing is that I can connect from my local developer machine, when running our frontend. Just as I can connect from wsl2 ubuntu cli.
On the Mongo side, I have whitelisted every possible ip address. On the AWS side, I have created the outbound security group policy required. Regarding the inbound, I think it is correct. I've allowed access on the ports 27000 - 28018.
Again - I'm new to AWS, so if anyone can tell me what it is I'm simply not understanding here, I would be very grateful
Thanks
open mongodb atlas Network Access
open 0.0.0.0/0 (includes your current IP address)

MongoParseError: option useCreateIndex is not supported

I tried to run the server in my MERN project but it gives me a MongoParseError.
My code is,
const mongoose = require("mongoose");
module.exports = async() => {
try {
const connectionParams = {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
};
await mongoose.connect("mongodb://localhost/todo-app", connectionParams);
console.log("Connected to database.");
} catch (error) {
console.log("Could not able to connect to database.", error);
}
};
And the error message was,
Listening on port ${port}...
Could not able to connect to database. MongoParseError: option usecreateindex is not supported
How to fix this?
This error occurs due to the Deprecation Warning Options.
To avoid this:
Remove useCreateIndex: true,
Now run the server.
You can also try:
Remove entire const connectionParams = {....};
Remove the comma and connectionParams parameter.
Now run the server.
Your final code should look like:
const mongoose = require("mongoose");
module.exports = async() => {
try {
await mongoose.connect("mongodb://localhost/todo-app");
console.log("Connected to database.");
} catch (error) {
console.log("Could not able to connect to database.", error);
}
};
Because useNewUrlParser, useUnifiedTopology, useFindAndModify, and useCreateIndex are no longer supported options. Mongoose 6 always behaves as if useNewUrlParser, useUnifiedTopology, and useCreateIndex are true, and useFindAndModify is false. So please remove these options from your code.
for more clarifications refer here

Can't connect to Mongo Atlas anyway

I am trying to connect to mongoDB atlas.But can't do it anyway.I have tried all options that found on the stackoverflow
My server.js is like as below
const express = require('express')
const next = require('next')
const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
/*
-------------- Mongo db connection -----------
*/
const mongoose = require('mongoose')
mongoose.connect('mongodb+srv://tintindenmark#gmail.com:*********#cluster0-f9upb.mongodb.net/test?retryWrites=true&w=majority', { useNewUrlParser: true });
mongoose.connection
.once('open', () => console.log('Good to go!'))
.on('error', (error) => {
console.warn('Warning', error);
});
/*
------------------------ Mongo db connection ends ------------------------
*/
app.prepare().then(() => {
const server = express()
server.get('/about', (req, res) => {
return app.render(req, res, '/about', req.query)
})
server.get('*', (req, res) => {
return handle(req, res)
})
server.listen(port, err => {
if (err) throw err
console.log(`> Ready on http://localhost:${port}`)
})
})
but i cant do it anyway.I have whitelisted IP addresses from atlast clusters.
Also tried without mongodb+srv.It didnt worked also
Always i am getting this errorMongoNetworkError: failed to connect to server [cluster0-shard-00-01-f9upb.mongodb.net:27017] on first connect [MongoError: Authentication failed.]
I also tried mongodb+srv://tintindenmark#gmail.com:musassmc42#cluster0-f9upb.mongodb.net:27017/test but it also didn't work
So what else i can do to connect??
My mongoose version is : 5.6.6
tintindenmark#gmail.com:musassmc42, this username:password is of your atlas account and not your database.
Created a new user and password for you. Try:
mongodb+srv://testuser:testpassword#cluster0-f9upb.mongodb.net:27017/test
And change all passwords.

Unhandled promise rejection: Error: URL malformed, cannot be parsed

I am new to aws and mongodb at the same time, so I'm stuck at a very basic point in trying to connect to my mongo databse, hosted on an amazon linux ec2 instance. The reason is, I'm not able to build the path to my database.
Here is what I'm trying to use:
mongoose.connect('mongod://ec2-user#ec2-XX-XX-XXX-XXX-XX.compute-1.amazonaws.com:27017/test' )
And here is the result of my test lambda function:
UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: URL malformed, cannot be parsed
I'm using mongodb 3.6.5.
Mongoose 5.x supports following syntax for authorization and also make sure you have not used any special character in url like #,-,+,>
mongoose.connect(MONGO_URL, {
auth: {
user: MONGO_DB_USER,
password: MONGO_DB_PASSWORD
}
})
Or if you want to remove deprication warning Avoid “current URL string parser is deprecated"
Add option useNewUrlParser
mongoose.connect(MONGO_URL, {
auth: {
user: MONGO_DB_USER,
password: MONGO_DB_PASSWORD
},
{ useNewUrlParser: true }
})
My issue was a more simple URI issue. Since there was an # character in the mongod address.
I had to use this:
return mongoose.connect(encodeURI(process.env.DB_CONNECT)); //added ');'
If you used the following URI in your environment file for example
MongoDB://<dbuser>:<dbpassword>#ds055915.mlab.com:55915/fullstack-vue-graphql
Make sure your password inMONGOD_URI does not have a special character like #. I had used # as part of my password character and was getting the error. After I removed special characters from my DB Password, all worked as expected.
In my case the below worked fine.
Inside db.js
const mongoose = require('mongoose');
const MONGODB_URI = "mongodb://host-name:27017/db-name?authSource=admin";
const MONGODB_USER = "mongouser";
const MONGODB_PASS = "myasri*$atIP38:nG*#o";
const authData = {
"user": MONGODB_USER,
"pass": MONGODB_PASS,
"useNewUrlParser": true,
"useCreateIndex": true
};
mongoose.connect(
MONGODB_URI,
authData,
(err) => {
if (!err) { console.log('MongoDB connection succeeded.'); }
else { console.log('Error in MongoDB connection : ' + JSON.stringify(err, undefined, 2)); }
}
);
Note:
My Node version is 10.x
MongoDb server version is 3.6.3
mongoose version is ^5.1.2
I just want update the answer from #anthony-winzlet, because I have same error and I has solve with this code.
mongoose.connect(url, {
auth: {
user:'usrkoperasi',
password:'password'
},
useNewUrlParser:true
}, function(err, client) {
if (err) {
console.log(err);
}
console.log('connect!!!');
});
I just add callback and useNewUrlParser:true. I use "mongoose": "^5.2.7",.
Happy coding!
If you deployed your app to Heroku make sure you updated the Config Vars as they are in your .env file. At least, this was my case.
I know this question has accepted answer, but this is what worked for me:
I'm using Mongoose 6.0.5 and Mongodb 5.0.6, with authentication enabled and with special character (%) in the password:
mongoose.connect('mongodb://localhost:27017', {
auth: { username: "myusername", password: "mypassword%" },
dbName: "mydbname",
authSource: "mydbname",
useNewUrlParser: true,
useUnifiedTopology: true,
}, function(err, db) {
if (err) {
console.log('mongoose error', err);
}
});
Many solutions had only user and pass for auth that needed username and password instead. Also it needed dbName to get access to mydb's collections.
I have same problem but problem with password
should'nt special character
password not use like this Admin#%+admin.com wrong
password use like this Admin right
or any password you wanna use