1

I'm getting connection timeout error in my server when i deployed my application in my local machine everything is working as expected but only for few bigger database queries i'm getting this error :

{ result:
   { result:
      { MongoNetworkError: connection 4 to localhost:27017 timed out
          at Socket.<anonymous> (/caching/node_modules/mongodb-core/lib/connection/connection.js:259:7)
          at Object.onceWrapper (events.js:277:13)
          at Socket.emit (events.js:189:13)
          at Socket._onTimeout (net.js:443:8)
          at ontimeout (timers.js:436:11)
          at tryOnTimeout (timers.js:300:5)
          at listOnTimeout (timers.js:263:5)
          at Timer.processTimers (timers.js:223:10)
        name: 'MongoNetworkError',
        errorLabels: [Array],
        [Symbol(mongoErrorContextSymbol)]: {} } } }
  • Possible duplicate of [MongoError: connection 0 to localhost:27017 timed out](https://stackoverflow.com/questions/41394850/mongoerror-connection-0-to-localhost27017-timed-out) – Raja Sekar Apr 15 '19 at 06:29

2 Answers2

4

The issue is your query is taking a long time to process. And mongodb has a default timeout configured. If the query takes longer than this default, it fails. Pass the required timeout as per your need to the connection parameter.

const mongoose = require('mongoose');
const option = {
    socketTimeoutMS: 30000,
    keepAlive: true,
    reconnectTries: 30000
};

mongoose.connect(mongoURI, option);
PrivateOmega
  • 2,509
  • 1
  • 17
  • 27
0

This parameters works for me:

  const MONGO_CLIENT = new MongoClient(process.env.MONGO_DB_URI, {
    useNewUrlParser: true, // Avoid deprecation warning
    useUnifiedTopology: true, // Avoid deprecation warning
    poolSize: 10, // Maintain up to 10 socket connections, default is 5
    serverSelectionTimeoutMS: 5000, // Keep trying to send operations for 5 seconds
    socketTimeoutMS: 300000, // Close sockets after 5 minutes of inactivity

  });
Java bee
  • 2,522
  • 1
  • 12
  • 25