Reputation: 71
I'm trying to connect a Node.js application with MongoDB Atlas trough Mongoose and I'm getting the following 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 (C:\Users\marin\Downloads\Project part2\Project part2\docker_app\node_modules\mongoose\lib\connection.js:797:32)
at C:\Users\marin\Downloads\Project part2\Project part2\docker_app\node_modules\mongoose\lib\index.js:332:10
at C:\Users\marin\Downloads\Project part2\Project part2\docker_app\node_modules\mongoose\lib\helpers\promiseOrCallback.js:32:5
at new Promise (<anonymous>)
at promiseOrCallback (C:\Users\marin\Downloads\Project part2\Project part2\docker_app\node_modules\mongoose\lib\helpers\promiseOrCallback.js:31:10)
at Mongoose._promiseOrCallback (C:\Users\marin\Downloads\Project part2\Project part2\docker_app\node_modules\mongoose\lib\index.js:1153:10)
at Mongoose.connect (C:\Users\marin\Downloads\Project part2\Project part2\docker_app\node_modules\mongoose\lib\index.js:331:20)
at connectDb (C:\Users\marin\Downloads\Project part2\Project part2\docker_app\src\connection.js:9:6)
at Server.<anonymous> (C:\Users\marin\Downloads\Project part2\Project part2\docker_app\server.js:27:3)
at Object.onceWrapper (events.js:519:28) {
reason: TopologyDescription {
type: 'Unknown',
servers: Map(1) {
'cluster0.huaic.mongodb.net:27017' => [ServerDescription]
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
logicalSessionTimeoutMinutes: undefined
}
}
My code is:
const mongoose = require("mongoose");
const User = require("./User.model");
const connection = '"mongodb://cluster0.huaic.mongodb.net/myFirstDatabase"';
const connectDb = () => {
return mongoose
.connect(connection)
.then((res) => {
return res;
})
.catch((error) => {
console.log(error);
});
};
module.exports = connectDb;
I've allowed access from every IP on mongodb atlas and when I try to connect directly to atlas everything works fine.
Upvotes: 2
Views: 897
Reputation: 45825
Make sure your connection string is like below. It should include your username
and password
:
"mongodb+srv://username:[email protected]/yourdatabasename?retryWrites=true&w=majority"
Set up a user that has that password
and that username
by going to Database Access
in your atlas account.
Upvotes: 1
Reputation: 74
For first, you have double quotes in the connection
variable. Secondly: it seems to me that mongoUri should include the username and password in the query string, right?
Upvotes: 1