We have an API working with MongoDB Atlas, connection works 99% of the time, but we occasionally get a MongoServerSelectionError: Server selection timed out after 30000 ms
on a specific endpoint for some reason. Like I said, it fails 2/3 times out of 100.
We are connecting like so:
const { MongoClient} = require('mongodb');
const client = new MongoClient(
process.env.MONGODB_CONNECTION_STRING,
{
useNewUrlParser: true,
useUnifiedTopology: true
}
);
module.exports = client.connect();
This is running on Netlify Functions, and whenever the function needs to use Mongo, it just awaits the connection promise.
Full error:
{
"errorType":"Runtime.UnhandledPromiseRejection",
"errorMessage":"MongoServerSelectionError: Server selection timed out after 30000 ms",
"reason":{
"errorType":"MongoServerSelectionError",
"errorMessage":"Server selection timed out after 30000 ms",
"reason":{
"type":"ReplicaSetNoPrimary",
"servers":{
},
"stale":false,
"compatible":true,
"heartbeatFrequencyMS":10000,
"localThresholdMS":15,
"setName":"atlas-13tibr-shard-0"
},
"stack":[
"MongoServerSelectionError: Server selection timed out after 30000 ms",
" at Timeout._onTimeout (/var/task/node_modules/mongodb/lib/sdam/topology.js:330:38)",
" at listOnTimeout (internal/timers.js:557:17)",
" at processTimers (internal/timers.js:500:7)"
]
},
"promise":{
},
"stack":[
"Runtime.UnhandledPromiseRejection: MongoServerSelectionError: Server selection timed out after 30000 ms",
" at process.<anonymous> (/var/runtime/index.js:35:15)",
" at process.emit (events.js:400:28)",
" at processPromiseRejections (internal/process/promises.js:245:33)",
" at processTicksAndRejections (internal/process/task_queues.js:96:32)"
]
}