How can I get the MongoDB Atlas cloud database to cooperate and connect to my Nodejs/Express app?

Issue

I’m getting a ‘MongoServerSelectionError’ while attempting to connect to the Atlas MongoDB cloud database. I’ve been working on this researching and trying different things to connect to the database but so far I’ve found no solution that works. I’m almost embarrased to say how long I’ve been working on this trying to find a solution to this problem. I’ve been racking my brain and searching SO, the MongoDB Community and the internet for days to no avail. The crazy part about it is that it was working at one time and now it isn’t. So it seems something has changed on MongoDB’s side. (see this post where someone else had the same problem and it mysteriously fixed itself:
https://www.mongodb.com/community/forums/t/cannot-connect-to-mongodb-on-atlats/126634

I’d hate to abandon MongoDB Atlas altogether for another cloud-based DB development solution, especially after putting in so much time and effort finding a solution, but I’m fresh out of ideas.

Here is what I’ve tried:

  1. Whitelisted my IP address and added the ‘access from anywhere’ device IP access to the Network Access: Whitelisting seems to be the most popular solution for most people, but didn’t work for me. Also, 0.0.0.0/0 IP whitelisting is a security risk.

    MongoDB Network Access

  2. Made sure that MongoDB is running as service in the Windows processes.
    Windows Task Manager

  3. Created an outbound rule for MongoDB in the Windows Firewall for ports 27015-27017:
    Windows Defender Firewall settings for MongoDB

  4. Tried using the appropriate MongoDB Atlas connection strings for MongoDB Compass and the Mongosh CLI.

Here is the stacktrace:

[nodemon] starting `node app.js`
        Server running in development mode on port 8001 
        TopologyDescription {
          type: 'ReplicaSetNoPrimary',
          servers: Map(3) {
            'cluster0-shard-00-01.nrx14.mongodb.net:27017' => ServerDescription {
              _hostAddress: new HostAddress('cluster0-shard-00-01.nrx14.mongodb.net:27017'),
              address: 'cluster0-shard-00-01.nrx14.mongodb.net:27017',
              type: 'Unknown',
              hosts: [],
              passives: [],
              arbiters: [],
              tags: {},
              minWireVersion: 0,
              maxWireVersion: 0,
              roundTripTime: -1,
              lastUpdateTime: 434689931,
              lastWriteDate: 0,
              error: [MongoNetworkError]
            },
            'cluster0-shard-00-02.nrx14.mongodb.net:27017' => ServerDescription {
              _hostAddress: new HostAddress('cluster0-shard-00-02.nrx14.mongodb.net:27017'),
              address: 'cluster0-shard-00-02.nrx14.mongodb.net:27017',
              type: 'Unknown',
              hosts: [],
              passives: [],
              arbiters: [],
              tags: {},
              minWireVersion: 0,
              maxWireVersion: 0,
              roundTripTime: -1,
              lastUpdateTime: 434689992,
              lastWriteDate: 0,
              error: [MongoNetworkError]
            },
            'cluster0-shard-00-00.nrx14.mongodb.net:27017' => ServerDescription {
              _hostAddress: new HostAddress('cluster0-shard-00-00.nrx14.mongodb.net:27017'),
              address: 'cluster0-shard-00-00.nrx14.mongodb.net:27017',
              type: 'Unknown',
              hosts: [],
              passives: [],
              arbiters: [],
              tags: {},
              minWireVersion: 0,
              maxWireVersion: 0,
              roundTripTime: -1,
              lastUpdateTime: 434689997,
              lastWriteDate: 0,
              error: [MongoNetworkError]
            }
          },
          stale: false,
          compatible: true,
          heartbeatFrequencyMS: 10000,
          localThresholdMS: 15,
          setName: 'atlas-ru0p0t-shard-0',
          logicalSessionTimeoutMinutes: undefined
        }
        [nodemon] app crashed - waiting for file changes before starting...

Here are the pertinent files:

package.json:

{
  "name": "y",
  "version": "1.0.0",
  "description": 
  "main": "index.js",
  "scripts": {
    "start": "cross-env NODE_ENV=production node app",
    "dev": "cross-env NODE_ENV=development nodemon app"

  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "connect-mongo": "^4.6.0",
    "cross-env": "^7.0.3",
    "dotenv": "^16.0.1",
    "express": "^4.18.1",
    "express-handlebars": "^6.0.6",
    "express-session": "^1.17.3",
    "mongoose": "^6.4.6",
    "morgan": "^1.10.0",
    "passport": "^0.6.0",
    "passport-google-oauth20": "^2.0.0"
  },
  "devDependencies": {
    "nodemon": "^2.0.19"
  }
}

app.js

const express = require("express");
const dotenv = require("dotenv");
const connectDB = require('./config/db')

// Load config
dotenv.config({ path: './config/config.env'})

connectDB()

const app = express();

const PORT = process.env.PORT || 8001

app.listen(PORT, () =>
    console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT} `)
)

db.js

const mongoose = require('mongoose')
const connectDB = async () => {
    try {
        const conn = await mongoose.connect(process.env.MONGO_URI, {
         // These params are no longer supported in Mongoose version 6
        // useNewUrlParser: true,
        // useUnifiedTopology: true,

        })

        console.log(`MongoDB Connected: ${conn.connection.host}`)
    } catch (err) {
        console.error(err.reason)
        process.exit(1)
    }
}

module.exports = connectDB

config.env

PORT=8888    
MONGO_URI=mongodb+srv://Username1:[email protected]/myDatabase?retryWrites=true&w=majority

Solution

After numerous troubleshooting steps, I used my cell phone to tether to my computer to see if the issue was my ISP gateway. I was able to connect with no problems connecting with my phone. At that point, I knew it was an ISP issue. To connect using your ISP’s internet, you have to open port 27017 on your gateway device. Search ‘port forwarding’ for your particular ISP to add port 27017 to the list of available ports. It’s not open by default for some ISPs like mine. Good coding!

Answered By – brohjoe

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published