Anurag Rawal
Anurag Rawal

Reputation: 55

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!

Upvotes: 1

Views: 663

Answers (4)

cconsta1
cconsta1

Reputation: 865

I solved the same issue recently by upgrading Node.js and npm. I used nvm (Node Version Manager) (install using brew install nvm for macOS):

First upgrade Node.js and npm

  1. Available Node.js Versions:
    nvm ls-remote
    
  2. Install the Latest Version of Node.js:
    nvm install node
    
  3. Use the Latest Version:
    nvm use node
    
  4. Set the Latest Version as Default:
    nvm alias default node
    
  5. Verify the Installed Versions:
    node -v
    npm -v
    

Then reinstall Dependencies

  1. Remove node_modules:
    rm -rf node_modules
    
  2. Install Dependencies:
    npm install
    

Finally restart Your Server

  1. Start Your Server:
    npm run dev
    

This worked for me! It turns out I was using a very old version of Node.js which somehow messed things up for the app.

Upvotes: 0

benjdan
benjdan

Reputation: 199

I had the same problem while using Node 19.6.0. I resolved it by upgrading Node to the latest version.

Upvotes: 1

Anurag Rawal
Anurag Rawal

Reputation: 55

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 [email protected]
  1. Using mongodb+srv:// instead of mongodb:// in the url to connect to the MongoDB cluster

Upvotes: 2

Navdeep Singh
Navdeep Singh

Reputation: 25

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.

Upvotes: -2

Related Questions