MongooseServerSelectionError: connection timed out at Model.$wrapCallback

How do I find the root cause of this error?

As of now I restart the MongoDB when this error is encountered. It would be great if I can get some pointers to debug this issue. I tried on net but couldn’t solve this issue.

Can multiple user requests going to node at the same time cause this?


MongooseServerSelectionError: connection timed out
    at Model.$wrapCallback (/root/cops/node_modules/mongoose/lib/model.js:5078:32)
    at /root/cops/node_modules/mongoose/lib/query.js:4510:21
    at /root/cops/node_modules/mongoose/lib/helpers/promiseOrCallback.js:32:5
    at new Promise (<anonymous>)
    at promiseOrCallback (/root/cops/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:10)
    at model.Query.exec (/root/cops/node_modules/mongoose/lib/query.js:4509:10)
    at Query.then (/root/cops/node_modules/mongoose/lib/query.js:4592:15)
    at runNextTicks (node:internal/process/task_queues:60:5)
    at process.processImmediate (node:internal/timers:442:9) {
  reason: TopologyDescription {
    type: 'Single',
    setName: null,
    maxSetVersion: null,
    maxElectionId: null,
    servers: Map(1) { '' => [ServerDescription] },
    stale: false,
    compatible: true,
    compatibilityError: null,
    logicalSessionTimeoutMinutes: null,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    commonWireVersion: 6

my mongo connection code is as follows

const mongooseOpts = {
  useUnifiedTopology: true,
  useNewUrlParser: true,
  useFindAndModify: false,
  // autoReconnect: true,
  // reconnectTries: Number.MAX_VALUE,
  // reconnectInterval: 1000,
  poolSize: 10,

mongoose.connect('mongodb://', mongooseOpts)
  .then(() => {
    console.log('Connected to database @ ' + new Intl.DateTimeFormat('en-IN', { timeStyle: 'medium', dateStyle: 'medium', timeZone: 'Asia/Kolkata' }).format(new Date()));
  .catch((err) => {
    console.log('Database connection failed on ' + new Intl.DateTimeFormat('en-IN', { timeStyle: 'medium', dateStyle: 'medium', timeZone: 'Asia/Kolkata' }).format(new Date()) + ', Err: ' + err);

Hey @Hemant_Parmar,

Thank you for reaching out!

  • Could you share the deployment details of your MongoDB server (e.g., standalone or replica set) along with the OS information?
  • Additionally, could you share the versions of MongoDB and Mongoose you are currently using?
  • When does the error occur? Is it consistently reproducible or intermittent?
  • Are there any specific actions or user operations that trigger this error?
  • Have you checked the MongoDB server logs for any relevant error messages?
  • Are there any indications of high traffic or increased load on the Node.js server when the error occurs?
  • Is there a longer idle time between your application and the database server?

The above information will help the community to assist you better.

Best regards,