Mongoose MongooseServerSelectionError: Server selection timed out after 30000 ms. Getting this error intermittently

Viewed 81

I have been trying to resolve the issue for the past one month but unable to do so. I have updated the nodejs version from 12.16.1 to 16.14.0 and updated mongoose from 5.9.12 to 6.3.0.

This is my current code.

client = mongoose.createConnection(dbConnectionString)//connection string is srv;

client.on('connected', function () {
      console.log(`connected to the DB`)
});

client.on('disconnected', function () {
    mongoose.connections.forEach(conn=> {
         const modelNames = Object.keys(conn.models);
         modelNames.forEach(modelName => {
              conn.deleteModel(modelName);
         })
    }
    console.log(`disconnected from db`);
});

client.on('error', function (err) {
     throw err;        
});


Surprisingly I face this issue when we receive lots of requests at a time. The mongo connection disconnects. Which in turn leads to serverselectiontimeout error. The method which I try to use is the mongoose.find()

async find(query, projection):Promise<any[]> {
    q = this.model.find(query, projection);
    return q.lean().exec().
}

I tried lot of ways to resolve this unable to do so. I tried directconnection: true but since, I the connection string is srv it couldn't be resolved. I increased the serverselectionTimeout but it has no use. The issue happens intermittently and not always. My application can take upto 1k requests at a time and can run smooth but more than that, the mongoose connection disconnects and I get mongooseServerSelection error timeout after 30000s for about 20% requests.

Node version: 16.14.0
mongoose: 6.3.0
mongodb: "4.1.3"

0 Answers
Related