mongoose
mongoose copied to clipboard
MongooseServerSelectionError - Could not connect to any servers in your MongoDB Atlas cluster - Bizarre error / situation
Prerequisites
- [X] I have written a descriptive issue title
- [X] I have searched existing issues to ensure the bug has not already been reported
Mongoose version
7.6.1
Node.js version
deno 1.37.2 (release, x86_64-pc-windows-msvc)
MongoDB server version
6.x
Typescript version (if applicable)
5.2.2
Description
This is very strange. Me and a colleague are working on the same project. He can connect to the database via Mongoose - same project - same git repo etc - I push changes and he can connect fine - same credentials - yet when I try I get the following error:
I can access the database via Mongo Compass no hassles. We created a new user and he could connect his end no problems, I could not...
mongoose.connect 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://www.mongodb.com/docs/atlas/security-whitelist/ at _handleConnectionErrors at NativeConnection.openUri at eventLoopTick (ext:core/01_core.js:197:13) at async file:///C:/projects/PROJECT-NAME/src/lib/db.ts:12:3
reason: TopologyDescription {
type: "ReplicaSetNoPrimary",
servers: Map(4) {
"REDACTED" => ServerDescription {
address: "REDACTED",
type: "Unknown",
hosts: [],
passives: [],
arbiters: [],
tags: {},
minWireVersion: 0,
maxWireVersion: 0,
roundTripTime: -1,
lastUpdateTime: 22102,
lastWriteDate: 0,
error: null,
topologyVersion: null,
setName: null,
setVersion: null,
electionId: null,
logicalSessionTimeoutMinutes: null,
primary: null,
me: null,
"$clusterTime": null
},
"REDACTED" => ServerDescription {
address: "REDACTED",
type: "Unknown",
hosts: [],
passives: [],
arbiters: [],
tags: {},
minWireVersion: 0,
maxWireVersion: 0,
roundTripTime: -1,
lastUpdateTime: 22102,
lastWriteDate: 0,
error: null,
topologyVersion: null,
setName: null,
setVersion: null,
electionId: null,
logicalSessionTimeoutMinutes: null,
primary: null,
me: null,
"$clusterTime": null
},
"REDACTED" => ServerDescription {
address: "REDACTED",
type: "Unknown",
hosts: [],
passives: [],
arbiters: [],
tags: {},
minWireVersion: 0,
maxWireVersion: 0,
roundTripTime: -1,
lastUpdateTime: 22102,
lastWriteDate: 0,
error: null,
topologyVersion: null,
setName: null,
setVersion: null,
electionId: null,
logicalSessionTimeoutMinutes: null,
primary: null,
me: null,
"$clusterTime": null
},
"REDACTED" => ServerDescription {
address: "REDACTED",
type: "Unknown",
hosts: [],
passives: [],
arbiters: [],
tags: {},
minWireVersion: 0,
maxWireVersion: 0,
roundTripTime: -1,
lastUpdateTime: 22102,
lastWriteDate: 0,
error: null,
topologyVersion: null,
setName: null,
setVersion: null,
electionId: null,
logicalSessionTimeoutMinutes: null,
primary: null,
me: null,
"$clusterTime": null
}
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
setName: "REDACTED",
maxElectionId: new ObjectId("7fffffff0000000000000181"),
maxSetVersion: 359,
commonWireVersion: 0,
logicalSessionTimeoutMinutes: null
},
code: undefined
Tried:
I switched back to using the Deno Mongo driver and I could connect no problem - I will use this for now so I can continue working but this is so strange.
// const client = new MongoClient(); // const username = Deno.env.get("MONGO_USERNAME"); // const password = Deno.env.get("MONGO_PASSWORD");
// const dbName = "REDACTED";
// try { // await client.connect({ // db: dbName, // tls: true, // servers: [ // { // host: "REDACTED", // port: 27017, // }, // { // host: "REDACTED", // port: 27017, // }, // { // host: "REDACTED", // port: 27017, // }, // ], // credential: { // username, // password, // db: "admin", // mechanism: "SCRAM-SHA-1", // }, // });
// console.log("Connected to MongoDB"); // } catch (error) { // console.log("Could not connect to MongoDB: ", error); // }
Tried I also deleted .deno and all dependencies from my local folder. Upgraded Node, upgrade npm.. Turned my firewall off Changed my DNS to Google and OpenDNS settings just in case.
And nothing...
Steps to Reproduce
deno init a new Deno project
- In main.ts:
- import mongoose from "npm:mongoose";
await mongoose.connect("mongodb+srv://
// Check to see connection status. console.log(mongoose.connection.readyState);
- Run with deno run --allow-read --allow-env --allow-sys --allow-net main.ts
- After some time I get that error, its not immediate, it seems to take the timeout amount of time to error out.
- MongooseServerSelectionError:
Expected Behavior
As explained I can connect in this exact project using the Mongo driver no issue but when I switch to mongoose it breaks.
I almost want to accept its some setup error because as mentioned my colleague, on pretty much same OS etc etc does not get this error but I can't see anything I'm doing differently.
Does the discussion here help at all? https://github.com/Automattic/mongoose/issues/13785
Another person ran into a similar issue here https://github.com/Automattic/mongoose/issues/13969 but it looks like they just closed it out without saying anything?
Does the discussion here help at all? #13785
Another person ran into a similar issue here #13969 but it looks like they just closed it out without saying anything?
This was me and my colleague actually - after realising it wasn't 'the exact same error', I committed my code and he tried on his end and was able to connect fine. While this almost surely points to environment I'd love any suggestions on what to check and or change. We went over it, tried various things and so far still can't connect. I've gone back to the 'native' deno mongo driver. This project probably won't need to make use of too many Mongoose's great features.
facing same issue for DocumentDB cluster
Hello, I have the same issue with deno and mongoose, but not solved yet. In my scenario, when I connect to the same MongoDB Atlas with the same URI from the same PC using mongosh.exe it connects, but not inside deno 1.37.2 and mongoose 7.6.3 on windows 10. The same happens trying to access to a different MongoDB instance inside my LAN, but it works when I use a local mongo DB in that PC (PC not working with deno+mongoose and Atlas). Using another laptop with the same configuration it works using the same WiFi than the PC, however when I change the laptop from my router's WiFi to a WIFI connection through mobile phone I have the same error. IMO, it is related to the mongoose driver for MongoDB connections.
So for me I was also able to connect perfectly with Compass from my computer - so whitelisting shouldn't be the issue and now that I've switched back to the native Mongo driver in Deno it works fine.
Hi, how did you switch back to the native Mongo driver in Deno?
I am importing mongoose as
import mongoose from "npm:[email protected]";
Initially had quite a struggle but managed with the following code:
`import "https://deno.land/x/[email protected]/load.ts"; import { MongoClient } from "https://deno.land/x/[email protected]/mod.ts";
const client = new MongoClient(); const username = Deno.env.get("MONGO_USERNAME"); const password = Deno.env.get("MONGO_PASSWORD");
const dbName = DB_NAME;
try { await client.connect({ db: dbName, tls: true, servers: [ { host: YOUR-DB-URL, port: 27017, }, { host: YOUR-DB-URL, port: 27017, }, { host: YOUR-DB-URL, port: 27017, }, ], credential: { username, password, db: "admin", mechanism: "SCRAM-SHA-1", }, });
console.log("Connected to MongoDB"); } catch (error) { console.log("Could not connect to MongoDB: ", error); }
export const mongo_conn = client.database(dbName); `
And then creating collection connections:
export const COLLECTION_NAME = mongo_conn.collection("COLLECTION_NAME_IN_MONGO");
Hope that helps.
Thanks for the answer. I see now that you are not using mongoose. In my case I need to use it. When I use mongosh with an external MongoDB Atlas, it works, also when I use my mongoose connection with a local URL, but not when I use my mongoose connection with an external MongoDB Atlas. It is strange.
Very strange, I'm unable to repro running the following script with Deno 1.38:
import mongoose from "npm:[email protected]";
await mongoose.connect('mongodb+srv://OMITTED?retryWrites=true&w=majority');
console.log(mongoose.connection.readyState);
$ time deno run --allow-read --allow-env --allow-sys --allow-net main.ts
1
^C
real 2m11.231s
user 0m0.958s
sys 0m0.126s
This might be a windows-specific thing, we should try running this script on Windows and see if we can repro. @ReturnXDev @jtgijon are you running Deno through powershell, git bash, or something else?
I'm running deno 1.37.2 from cmd/powershell. Using the same mongo db URI:
- I am not able to connect using a windows 10 laptop1 connected to my home WiFi or mobile phone connection
- I am able to connect using another a windows 10 desktop PC connected to my home WiFi
- I am able to connect using a windows 10 laptop2 connected to my home WiFi but not using mobile phone connection Deno/mongo versions are the same, but I have not found the reason it is not working in some scenarios
- I am able to connect if I use denodeploy with the mongodb pointing to MongoDB Atlas.
Your script returns in my case:
PS C:\OMITTED> deno run --allow-all .\testmongo.ts error: Uncaught (in promise) 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://www.mongodb.com/docs/atlas/security-whitelist/ at _handleConnectionErrors (file:///C:/OMITTED/node_modules/.deno/[email protected]/node_modules/mongoose/lib/connection.js:805:11) at NativeConnection.openUri (file:///C:/OMITTED/node_modules/.deno/[email protected]/node_modules/mongoose/lib/connection.js:780:11) at eventLoopTick (ext:core/01_core.js:197:13) at async file:///C:/OMITTED/testmongo.ts:3:1
We did some digging on this today. The only thing we've been able to find is that the MongoDB Node driver seems to be trying to connect to 127.0.0.1
, below is part of what mongoose.connections
outputs:
s: {
url: "mongodb://127.0.0.1:53486/mongoose_test"
Even though we're connecting to an Atlas URL. Will continue to debug this.
Hi. In my case the url is pointing correctly
Expand:s: {
url: "mongodb+srv://USER:[email protected]/?retryWrites=true&w=majority",
s: { url: "mongodb+srv://USER:[email protected]/?retryWrites=true&w=majority", bsonOptions: { raw: false, useBigInt64: false, promoteLongs: true, promoteValues: true, promoteBuffers: false, ignoreUndefined: false, bsonRegExp: false, serializeFunctions: false, fieldsAsRaw: {}, enableUtf8Validation: true }, namespace: MongoDBNamespace { db: "admin", collection: undefined }, hasBeenClosed: false, sessionPool: ServerSessionPool { client: [Circular *3], sessions: List { count: 0, head: [Object] } }, activeSessions: Set(0) {}, options: [Getter], readConcern: [Getter], writeConcern: [Getter], readPreference: [Getter], isMongoClient: [Getter] }, connectionLock: undefined, topology: Topology { _events: [Object: null prototype] { topologyDescriptionChanged: [Function (anonymous)], open: [Function: bound onceWrapper] { listener: [Function (anonymous)] }, connectionPoolCreated: [Function (anonymous)], connectionPoolReady: [Function (anonymous)], connectionPoolCleared: [Function (anonymous)], connectionPoolClosed: [Function (anonymous)], connectionCreated: [Function (anonymous)], connectionReady: [Function (anonymous)], connectionClosed: [Function (anonymous)], connectionCheckOutStarted: [Function (anonymous)], connectionCheckOutFailed: [Function (anonymous)], connectionCheckedOut: [Function (anonymous)], connectionCheckedIn: [Function (anonymous)], commandStarted: [Function (anonymous)], commandSucceeded: [Function (anonymous)], commandFailed: [Function (anonymous)], serverOpening: [Function (anonymous)], serverClosed: [Function (anonymous)], serverDescriptionChanged: [Function (anonymous)], topologyOpening: [Function (anonymous)], topologyClosed: [Function (anonymous)], error: [Function (anonymous)], timeout: [Function (anonymous)], close: [Function (anonymous)], serverHeartbeatStarted: [Function (anonymous)], serverHeartbeatSucceeded: [Function (anonymous)], serverHeartbeatFailed: [Function (anonymous)] }, _eventsCount: 27, _maxListeners: undefined, client: [Circular *3], selectServerAsync: [Function (anonymous)], s: { id: 0, options: [Object: null prototype] { hosts: [Array], credentials: [MongoCredentials], compressors: [Array], connectTimeoutMS: 30000, directConnection: false, driverInfo: [Object], enableUtf8Validation: true, forceServerObjectId: false, heartbeatFrequencyMS: 10000, keepAlive: true, keepAliveInitialDelay: 120000, loadBalanced: false, localThresholdMS: 15, maxConnecting: 2, maxIdleTimeMS: 0, maxPoolSize: 100, minPoolSize: 0, minHeartbeatFrequencyMS: 500, monitorCommands: false, noDelay: true, pkFactory: [Object], raw: false, readPreference: [ReadPreference], retryReads: true, retryWrites: true, serverSelectionTimeoutMS: 30000, socketTimeoutMS: 0, srvMaxHosts: 0, srvServiceName: "mongodb", writeConcern: [WriteConcern], waitQueueTimeoutMS: 0, zlibCompressionLevel: 0, dbName: "test", userSpecifiedAuthSource: false, userSpecifiedReplicaSet: false, srvHost: "cluster0.XYZ.mongodb.net", tls: true, mongoLoggerOptions: [Object], metadata: [Object], replicaSet: "atlas-k5jkmw-shard-0", [Symbol("@@mdb.enableMongoLogger")]: false }, seedlist: [ new HostAddress('ac-f27a7um-shard-00-00.xyz.mongodb.net.:27017'), new HostAddress('ac-f27a7um-shard-00-01.xyz.mongodb.net.:27017'), new HostAddress('ac-f27a7um-shard-00-02.xyz.mongodb.net.:27017') ], state: "closed", description: TopologyDescription { type: "ReplicaSetNoPrimary", servers: [Map], stale: false, compatible: true, heartbeatFrequencyMS: 10000, localThresholdMS: 15, setName: "atlas-k5jkmw-shard-0", maxElectionId: new ObjectId("7fffffff0000000000000328"), maxSetVersion: 9, commonWireVersion: 0, logicalSessionTimeoutMinutes: null }, serverSelectionTimeoutMS: 30000, heartbeatFrequencyMS: 10000, minHeartbeatFrequencyMS: 500, servers: Map(0) {}, credentials: MongoCredentials { username: "USER", password: "PASS", source: "admin", mechanism: "DEFAULT", mechanismProperties: {} }, clusterTime: { clusterTime: new Timestamp({ t: 1703059095, i: 10 }), signature: [Object] }, connectionTimers: Set(0) {}, detectShardedTopology: [Function: detectShardedTopology], detectSrvRecords: [Function: detectSrvRecords], srvPoller: SrvPoller { _events: [Object: null prototype] {}, _eventsCount: 0, _maxListeners: undefined, srvHost: "cluster0.XYZ.mongodb.net", srvMaxHosts: 0, srvServiceName: "mongodb", rescanSrvIntervalMS: 60000, heartbeatFrequencyMS: 10000, haMode: false, generation: 0, _timeout: undefined, [Symbol(kCapture)]: false } }, [Symbol(kCapture)]: false, [Symbol(waitQueue)]: List { count: 0, head: { next: [Circular *4], prev: [Circular *4], value: null } } }, [Symbol(kCapture)]: false, [Symbol(options)]: [Object: null prototype] { hosts: [ new HostAddress('ac-f27a7um-shard-00-00.XYZ.mongodb.net.:27017'), new HostAddress('ac-f27a7um-shard-00-01.XYZ.mongodb.net.:27017'), new HostAddress('ac-f27a7um-shard-00-02.XYZ.mongodb.net.:27017') ], credentials: MongoCredentials { username: "USER", password: "PASS", source: "admin", mechanism: "DEFAULT", mechanismProperties: {} }, compressors: [ "none" ], connectTimeoutMS: 30000, directConnection: false, driverInfo: { name: "Mongoose", version: "7.6.3" }, enableUtf8Validation: true, forceServerObjectId: false, heartbeatFrequencyMS: 10000, keepAlive: true, keepAliveInitialDelay: 120000, loadBalanced: false, localThresholdMS: 15, maxConnecting: 2, maxIdleTimeMS: 0, maxPoolSize: 100, minPoolSize: 0, minHeartbeatFrequencyMS: 500, monitorCommands: false, noDelay: true, pkFactory: { createPk: [Function: createPk] }, raw: false, readPreference: ReadPreference { mode: "primary", tags: undefined, hedge: undefined, maxStalenessSeconds: undefined, minWireVersion: undefined }, retryReads: true, retryWrites: true, serverSelectionTimeoutMS: 30000, socketTimeoutMS: 0, srvMaxHosts: 0, srvServiceName: "mongodb", writeConcern: WriteConcern { w: "majority" }, waitQueueTimeoutMS: 0, zlibCompressionLevel: 0, dbName: "test", userSpecifiedAuthSource: false, userSpecifiedReplicaSet: false, srvHost: "cluster0.XYZ.mongodb.net", tls: true, mongoLoggerOptions: { componentSeverities: { command: "off", topology: "off", serverSelection: "off", connection: "off", default: "off" }, maxDocumentLength: 1000, logDestination: { write: [Function: write] } }, metadata: { driver: { name: "nodejs|Mongoose", version: "5.9.0|7.6.3" }, platform: "Deno v1.37.2, LE", os: { name: "win32", architecture: "x64", version: "10.0.19045", type: "Windows_NT" } }, replicaSet: "atlas-k5jkmw-shard-0", [Symbol("@@mdb.enableMongoLogger")]: false } }, "$initialConnection": Promise {MongoServerSelectionError: Server selection timed out after 30000 ms at Timeout._onTimeout (file:///C:/Users/.../[email protected]/node_modules/mongodb/lib/sd am/topology.js:278:38) at cb (ext:deno_node/internal/timers.mjs:63:31) at Object.action (ext:deno_web/02_timers.js:151:11) at handleTimerMacrotask (ext:deno_web/02_timers.js:65:10) at eventLoopTick (ext:core/01_core.js:189:21) { reason: TopologyDescription { type: "ReplicaSetNoPrimary", servers: Map(3) { "ac-f27a7um-shard-00-00.XYZ.mongodb.net:27017" => [ServerDescription], "ac-f27a7um-shard-00-01.XYZ.mongodb.net:27017" => [ServerDescription], "ac-f27a7um-shard-00-02.XYZ.mongodb.net:27017" => [ServerDescription] }, stale: false, compatible: true, heartbeatFrequencyMS: 10000, localThresholdMS: 15, setName: "atlas-k5jkmw-shard-0", maxElectionId: new ObjectId("7fffffff0000000000000328"), maxSetVersion: 9, commonWireVersion: 0, logicalSessionTimeoutMinutes: null }, code: undefined, [Symbol(errorLabels)]: Set(0) {} } } }
hi, i have the same problem here...sometimes work...sometimes continue to throw this error...any solution?
Connection error: MongoServerSelectionError: Server selection timed out after 30000 ms
1|app | at EventTarget.<anonymous> (/home/marco/node_modules/mongodb/lib/sdam/topology.js:276:34)
1|app | at [nodejs.internal.kHybridDispatch] (node:internal/event_target:741:20)
1|app | at EventTarget.dispatchEvent (node:internal/event_target:683:26)
1|app | at abortSignal (node:internal/abort_controller:368:10)
1|app | at TimeoutController.abort (node:internal/abort_controller:402:5)
1|app | at Timeout.<anonymous> (/home/marco/node_modules/mongodb/lib/utils.js:1010:92)
1|app | at listOnTimeout (node:internal/timers:569:17)
1|app | at process.processTimers (node:internal/timers:512:7) {
1|app | reason: TopologyDescription {
1|app | type: 'ReplicaSetNoPrimary',
1|app | servers: Map(3) {
1|app | 'ac-luzptfw-shard-00-01.svn9sb8.mongodb.net:27017' => [ServerDescription],
1|app | 'ac-luzptfw-shard-00-02.svn9sb8.mongodb.net:27017' => [ServerDescription],
1|app | 'ac-luzptfw-shard-00-00.svn9sb8.mongodb.net:27017' => [ServerDescription]
1|app | },
1|app | stale: false,
1|app | compatible: true,
1|app | heartbeatFrequencyMS: 10000,
1|app | localThresholdMS: 15,
1|app | setName: 'atlas-eosskd-shard-0',
1|app | maxElectionId: null,
1|app | maxSetVersion: null,
1|app | commonWireVersion: 0,
1|app | logicalSessionTimeoutMinutes: null
1|app | },
1|app | code: undefined,
1|app | [Symbol(errorLabels)]: Set(0) {}
1|app | }
1|app | ReplicaSetNoPrimary error. Check your MongoDB replica set configuration.
1|app | You have triggered an unhandledRejection, you may have forgotten to catch a Promise rejection:
1|app | 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://www.mongodb.com/docs/atlas/security-whitelist/
my cluster allow connection from every ip...so is not a mongodb atlas whitelist problem.
@justoverclockl your error is unrelated. The ReplicaSetNoPrimary
means that Mongoose can't find a primary in your replica set - maybe there's a replica set failover or some version upgrade in progress?
I have the same problem with my MERN app, I deployed my app in Render and it works great by 2 - 3 minutes, and then the logs show me this, someone fix it?
err = new ServerSelectionError(); ^ 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://www.mongodb.com/docs/atlas/security-whitelist/ at _handleConnectionErrors (/opt/render/project/src/node_modules/mongoose/lib/connection.js:875:11) at NativeConnection.openUri (/opt/render/project/src/node_modules/mongoose/lib/connection.js:826:11) { reason: TopologyDescription { type: 'ReplicaSetNoPrimary', servers: Map(3) { 'ac-eijtew4-shard-00-00.sxjdq6u.mongodb.net:27017' => ServerDescription { address: 'ac-eijtew4-shard-00-00.sxjdq6u.mongodb.net:27017', type: 'Unknown', hosts: [], passives: [], arbiters: [], tags: {}, minWireVersion: 0, maxWireVersion: 0, roundTripTime: -1, lastUpdateTime: 776818059, lastWriteDate: 0, error: MongoNetworkError: 40D858D4807F0000:error:0A000438:SSL routines:ssl3_read_bytes:tlsv1 alert internal error:../deps/openssl/openssl/ssl/record/rec_layer_s3.c:1590:SSL alert number 80
@DevSebasVelez your issue is unrelated
Original issue seems to only happen on Windows, only on Deno, only with Atlas, only on certain WiFi, and only on Mongoose 7. I'm able to repro with Mongoose 7.6.3 on @IslandRhythms 's machine, but the issue comes down to the fact that tls.connect()
hangs here. The socket never emits any events. There isn't much more we can do to fix this particular error, other than recommend upgrading to Mongoose 8, which seems to be unaffected.
i was facing an error error: 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://www.mongodb.com/docs/atlas/security-whitelist/
even i change the IP Access List Entry to all for me the problem was the mongoose version i guess right now it is working fine with
npm i [email protected]
must try maybe help
@jitenderChoudhary1 Thanks so much. Completely stuck on this as well and all fixed with npm i [email protected]
@jitenderChoudhary1 Thanks a dozen. Was having this issue as well, and it was fixed by installing 8.1.1. ✌️
I'm having the same issue.