Next.js Discord

Discord Forum

MongoServerSelectionError that happens occasionally using Vercel

Unanswered
American posted this in #help-forum
Open in Discord
Avatar
AmericanOP
I am running a custom NodeJS server on Vercel and I've integrated MongoDB to it.

Occasionally I am getting this 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://www.mongodb.com/docs/atlas/security-whitelist/
    at _handleConnectionErrors (/var/task/node_modules/mongoose/lib/connection.js:816:11)
    at NativeConnection.openUri (/var/task/node_modules/mongoose/lib/connection.js:791:11)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at start (/vercel/path0/src/index.ts:99:5) {
  reason: TopologyDescription {
    type: 'ReplicaSetNoPrimary',
    servers: Map(3) {
      'ac-dgdfro8-shard-00-02.pzjcs9a.mongodb.net:27017' => [ServerDescription],
      'ac-dgdfro8-shard-00-00.pzjcs9a.mongodb.net:27017' => [ServerDescription],
      'ac-dgdfro8-shard-00-01.pzjcs9a.mongodb.net:27017' => [ServerDescription]
    },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    setName: 'atlas-cce8jf-shard-0',
    maxElectionId: null,
    maxSetVersion: null,
    commonWireVersion: 0,
    logicalSessionTimeoutMinutes: null
  },
  code: undefined
}

And therefore my mongoose requests are timing out, e.g. User.findOne()...

I have allowed access from anywhere in mongoDB atlas. The error only occurs rarely, most of the time it is working as intended.

I have found these posts to the exact same problem but none of them provide a solution:
https://stackoverflow.com/questions/78462688/mongodb-occasional-500-error-in-production
https://stackoverflow.com/questions/78419922/unhandled-rejection-mongoserverselectionerror
Locally I never get this error, also using the prod mongoose connection string, so it's not a MongoDB issue.
Any ideas?

0 Replies