Client network socket disconnected before secure TLS connection was established

I am using MongoClient in NodeJs to carry out Db operations, I am running into connection and db caching issues,
I’m getting the following error in my application -
error 1 -

Error: Client network socket disconnected before secure TLS connection was established
    at connResetException (internal/errors.js:609:14)
    at TLSSocket.onConnectEnd (_tls_wrap.js:1557:19)
    at Object.onceWrapper (events.js:420:28)
    at TLSSocket.emit (events.js:326:22)
    at TLSSocket.EventEmitter.emit (domain.js:483:12)
    at endReadableNT (_stream_readable.js:1241:12)
    at processTicksAndRejections (internal/process/task_queues.js:84:21) {
  name: 'MongoNetworkError'

error 2-

MongoServerSelectionError: Server selection timed out after 30000 ms
    at Timeout._onTimeout (/var/task/node_modules/mongodb/lib/core/sdam/topology.js:430:30)
    at listOnTimeout (internal/timers.js:554:17)
    at processTimers (internal/timers.js:497:7) {
  reason: TopologyDescription {
    type: 'ReplicaSetNoPrimary',
    setName: 'atlas-3kud01-shard-0',
    maxSetVersion: null,
    maxElectionId: null,
    servers: Map {
      'productioneuro-shard-00-00.vfau2.mongodb.net:27017' => [ServerDescription],
      'productioneuro-shard-00-01.vfau2.mongodb.net:27017' => [ServerDescription],
      'productioneuro-shard-00-02.vfau2.mongodb.net:27017' => [ServerDescription]
    },
    stale: false,
    compatible: true,
    compatibilityError: null,
    logicalSessionTimeoutMinutes: 30,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    commonWireVersion: 9
  }
}

Following is my DB connection and closing code-** I call the client method while going any db operation like findOne, insertOne, etc
And closeDBConnection right before returning the API response.

import { MongoClient, Db } from "mongodb";

let cachedDb: Db = null;
let mongoClient: MongoClient = null;

export const client = async (): Promise<Db> => {
  if (cachedDb && await mongoClient.isConnected()) {
    console.info("cached db connection established");
    return cachedDb;
  }
  
  mongoClient = new MongoClient('db URL here', {
    useUnifiedTopology: true,
    useNewUrlParser: true,
    connectTimeoutMS: 90000,
    poolSize: 10
  });
  try {
    await mongoClient.connect();

    if (await !mongoClient.isConnected()) {
      await mongoClient.connect(err => {
        if (err) {
          console.error("Error : ", err);
          throw new Error(`Unable to connect MongoDb Client, Reason: ${err}`
          );
        }
      });
    }

    cachedDb = await mongoClient.db(await "DB name here");
    console.info("db connection established");
    return cachedDb;
  } catch (error) {
    console.error("Error in connecting to DB => ", error);
    throw error;
  }
};

export const closeDBConnection = async () => {
  try {
    if( mongoClient != null ){
      await mongoClient.close();
      mongoClient = null;
      cachedDb = null;

      console.log("db connection closed");
      return true;
    } 
  } catch (error) {
    console.log("Error in closeDBConnection => ", error);
    return false;
  } 
};
2 Likes

Hi @Aniruddha_Raje.
Can you please confirm that you have added your IP address to IP Access List in Network Access tab of Atlas menu?
Also, please make sure that you are not using any firewall.
Once that is done, please try to connect again.

In case you have any doubts, please feel free to reach out to us.

Thanks and Regards.
Sourabh Bagrecha,
Curriculum Services Engineer

2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.