node.jsmongodbexpressmongoosemongodb-cluster

Connection to MongoDB cluster getting failed through NodeJS


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:

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!


Solution

  • Solution involves two steps

    1. Updating the mongoose package manually. I had the old mongoose package involved which was depreciated.
    npm install mongoose@latest
    

    OR (to specify the version)

    npm install mongoose@8.4.0
    
    1. Using mongodb+srv:// instead of mongodb:// in the url to connect to the MongoDB cluster