Issue I am facing
I am working on the ExpressJS web services project. We have created a free cluster in MongoDB Atlas and I am trying to connect to the DB using the connection string provided by the website itself. I have whitelisted my own IP and made it accessible from anywhere as well but still nothing has worked yet. To what I think my code is okay as I was able to connect to the localhost database. But I am still mentioning it below for better review.
The code:
const express = require('express');
const bodyParser = require('body-parser')
const cors = require('cors')
const mongoose = require('mongoose');
const app = express();
const port = 8000;
// Encode username and password for mongodb as URI encoded component
const username = encodeURIComponent("<username>");
const password = encodeURIComponent("<password>")
// const mongoDbUrl = `mongodb://${username}:${password}@host:port/database`;
// const mongoDbUrl = `mongodb://${username}:${password}@diversity-of-living-clu.hqwcott.mongodb.net`;
const mongoDbUrl = "mongodb://<username>:<password>@diversity-of-living-clu.hqwcott.mongodb.net/"
// mongodb://<username>:<password>@diversity-of-living-clu.hqwcott.mongodb.net/3380DiversityOfLiving-data?retryWrites=true&w=majority&appName=diversity-of-living-cluster
// Initialising options for cors
const corsOptions = {
origin: "*",
credentials: true
}
app.use(bodyParser.json());
app.use(cors(corsOptions));
// Routers
const numbeoRouter = require('./DiversityOfLiving-Routers/NumbeoRouterAra65');
const userRouter = require('./DiversityOfLiving-Routers/UserRouterJpa72');
const faqRouter = require('./DiversityOfLiving-Routers/FAQRouterJpa72');
const countryCountRouter = require('./DiversityOfLiving-Routers/CountryCountRouterJpa72');
const countryDataRouter = require('./DiversityOfLiving-Routers/CountryDataRouterAra65');
// Using Routers
app.use('/numbeo', numbeoRouter);
app.use('/faq', faqRouter);
app.use('/countrycount', countryCountRouter);
app.use('/user', userRouter);
app.use('/countrydata', countryDataRouter);
app.listen(port, function () {
console.log('Express server listening on: http://localhost:' + port);
mongoose.connect(mongoDbUrl, { useNewUrlParser: true, useUnifiedTopology: true, connectTimeoutMS: 10000 })
.then(() => {console.log("Connected to MongoDB");})
.catch((err) => {console.log("Error connecting to MongoDB:", err.message, err.stack);})
});
The solutions that I have tried:
- Both SRV and Non-SRV URLs
- Whitelisted my IP and made it available from anywhere as well.
The below is the error that I am getting:
Error connecting to MongoDB: 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/ 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/
But I do not think that is the issue as I was able to connect to the cluster using my MongoDB Compass, Mongosh and VS Code MongoDB extension.
Open to any reviews to the code and to try new solutions as well. Thank you!
3
Answers
Solution involves two steps
mongodb+srv://
instead ofmongodb://
in the url to connect to the MongoDB clusterYou’re receiving an error because your current IP address isn’t on the whitelist for your MongoDB Atlas cluster. To resolve this, you’ll need to add your IP address to the whitelist. Here’s how you can do it:
Log in to MongoDB Atlas:
Go to the MongoDB Atlas website
Log in with your credentials.
Access Your Cluster:
After logging in, navigate to your project that contains the cluster you want to access.
Click on the cluster name to open the cluster details.
In the left-hand menu, click on "Network Access".
Add IP Address:
Click on the "Add IP Address" button.
In the dialogue box that appears, you can:
Whitelist your current IP address by clicking "Add Current IP Address". This will automatically detect and add your current IP.
Add a specific IP address by entering it manually in the "Whitelist Entry" field.
Allow access from anywhere (not recommended for production environments) by entering 0.0.0.0/0.
Confirm and Save:
After entering the IP address, click "Confirm".
Make sure to click "Save" to apply the changes.
Wait for Changes to Propagate:
It may take a few minutes for the changes to propagate and take effect.
Retry Connecting:
After whitelisting your IP address, try connecting to your MongoDB Atlas cluster again.
Additional Resources
For more detailed instructions, you can refer to the MongoDB Atlas documentation on IP whitelisting:
MongoDB Atlas IP Whitelisting
By following these steps, you should be able to resolve the connection error and successfully connect to your MongoDB Atlas cluster.
I think you need to change the network access IP to
0.0.0.0/0
for your MongoDB Atlas cluster under security section. It should work fine. If not, try connecting your system to your mobile hotspot. Sometimes, there are network barriers that prevent the server from accessing the IP address.