简体   繁体   中英

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

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 网络访问

  2. Made sure that MongoDB is running as service in the Windows processes. Windows 任务管理器


  3. Created an outbound rule for MongoDB in the Windows Firewall for ports 27015-27017: MongoDB 的 Windows Defender 防火墙设置

  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:Password1234@cluster0.nrx14.mongodb.net/myDatabase?retryWrites=true&w=majority

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM