question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Cannot connect to a MongoDB on Mongo Atlas

See original GitHub issue

Do you want to request a feature or report a bug? bug

What is the current behavior? The connection to a MongoDB hosted on Mongo Atlas suddenly throws out an error. I have been searching on the Internet (Stackoverflow, …) for a day about this bug, but haven’t been able to figure out why it happens. Here are the detailed configs and error:

  • Connections from any IPs are allowed image

  • Connection code

    try {
        await mongoose.connect(process.env.MONGO_URI)
        console.log('Connected to MongoDB')
    } catch (err) {
        console.error(err)
    }
    
  • Connection string’s format

    process.env.MONGO_URI = mongodb+srv://<username>:<password>@<cluster>.asdf1234.mongodb.net/<dbname>?retryWrites=true&w=majority
    
  • Error

    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/
        at NativeConnection.Connection.openUri (/home/node/app/node_modules/mongoose/lib/connection.js:796:32)
        at /home/node/app/node_modules/mongoose/lib/index.js:328:10
        at /home/node/app/node_modules/mongoose/lib/helpers/promiseOrCallback.js:32:5
        at new Promise (<anonymous>)
        at promiseOrCallback (/home/node/app/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:10)
        at Mongoose._promiseOrCallback (/home/node/app/node_modules/mongoose/lib/index.js:1149:10)
        at Mongoose.connect (/home/node/app/node_modules/mongoose/lib/index.js:327:20)
        at /home/node/app/src/index.ts:33:20
        at step (/home/node/app/src/index.ts:33:23)
        at Object.next (/home/node/app/src/index.ts:14:53) {
    reason: TopologyDescription {
        type: 'ReplicaSetNoPrimary',
        servers: Map(3) {
        'devcluster-shard-00-01.asdf1234.mongodb.net:27017' => [ServerDescription],
        'devcluster-shard-00-00.asdf1234.mongodb.net:27017' => [ServerDescription],
        'devcluster-shard-00-02.asdf1234.mongodb.net:27017' => [ServerDescription]
        },
        stale: false,
        compatible: true,
        heartbeatFrequencyMS: 10000,
        localThresholdMS: 15,
        setName: 'atlas-11mhge-shard-0',
        logicalSessionTimeoutMinutes: undefined
    }
    
  • Dependencies’ version

    "mongoose": "^6.0.8"
    "typescript": "^4.3.5"
    

If the current behavior is a bug, please provide the steps to reproduce.

Create an Express app with the dependencies, MongoDB connection string, connection code, network access config as above. Then run the app

tsconfig.json

{
  "name": "auth",
  "version": "1.0.0",
  "description": "",
  "main": "./build/index.js",
  "types": "./build/index.d.ts",
  "files": [
    "build/**/*"
  ],
  "scripts": {
    "format": "prettier --write --ignore-unknown .",
    "test": "jest --watchAll --no-cache --config './src/test/jest.config.ts'",
    "test:ci": "jest --config './src/test/jest.config.ts'",
    "build": "tsc -p tsconfig.build.json",
    "start:dev": "ts-node-dev --poll src/index.ts",
    "start:stg": "node build/index.js",
    "start:prod": "node build/index.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1",
    "express-async-errors": "^3.1.1",
    "express-validator": "^6.12.0",
    "jsonwebtoken": "^8.5.1",
    "mongoose": "^6.0.8"
  },
  "devDependencies": {
    "@types/express": "^4.17.13",
    "@types/jest": "^27.0.1",
    "@types/jsonwebtoken": "^8.5.5",
    "@types/supertest": "^2.0.11",
    "jest": "^27.0.6",
    "mongodb-memory-server": "^7.4.2",
    "prettier": "2.3.2",
    "supertest": "^6.1.6",
    "ts-jest": "^27.0.5",
    "ts-node-dev": "^1.1.8",
    "typescript": "^4.3.5"
  }
}

What is the expected behavior?

Connections to MongoDB on Atlas should be successful.

What are the versions of Node.js, Mongoose and MongoDB you are using? Note that “latest” is not a version.

  • Nodejs: v16.8.0
  • Mongoose: 6.0.8
  • MongoDB: 4.4.9

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:6

github_iconTop GitHub Comments

1reaction
vkarpov15commented, Oct 4, 2021

@TranXuanHoang the issue is this: “certificate is not yet valid”. According to this SO, this may be indicative of system time issues on your machine. Can you please make sure your system time is accurate?

Also, are you able to connect by using the mongodb:// connection string rather than the mongodb+srv:// string?

0reactions
TranXuanHoangcommented, Oct 5, 2021

@vkarpov15 Thank you for your suggestion! I actually run an Express.js app inside a node alpine Docker container with time automatically set up to local time. Last weekend the code to connect to a MongoDB hosted on Mongo Atlas suddenly failed with the error I shared with you above. However, after waiting for 2 days, now the connection has gone back to normal - without any new revisions added to the source code or changing any configurations. I still don’t know why such strange thing happened, but anyway I am able to continue focusing on writing queries inside my source code to interact with the database again. Once again thank you very much for checking and replying to my question.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Can't connect to mongodb.Could not connect to any servers in ...
First try to Allow Access From Anywhere. If it works it is most likely because you whitelisted an IP address that is not...
Read more >
Error at connecting to MongoDb Atlas Server - Stack Overflow
I have had this issue connecting to a MongoDB Atlas cluster. I have had to resolve this issue twice because I was working...
Read more >
Can't connect to MongoDB atlas serverless instance
Hi, i have a MongoDB serverless instance but i can't connect to that. I am using the connection string that mongo atlas gives...
Read more >
cannot connect to mongo atlas from aws instance #462 - GitHub
This can be worked around by upgrading your MongoDB version to 4.2 (which supports the newer ciphers) or by downgrading your instance size,...
Read more >
Cannot connect to MongoDB atlas - Netlify Support Forums
Can anyone guide me on how to connect my create-react-app, express server all to mongo atlas without running into CORS issues? It says...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found