mongo.isConnected alternative for node driver v 4+

Hello,

I have actually two questions regarding the v4 of the driver:

  1. Since isConnected is no longer used, I notice that there are some libraries that check the isConnected. Is there any alternative for MongoClient.isConnected, or with what should I replace the isConnected check?

  2. Is it safe to use the nodejs mongodb driver v4 + mongo 5 already in production, or is it recommended to wait for it few weeks/months?

Thanks and best regards
Tony

I came across the same question. How do I check if the connection is still alive ?
(without creating a disconnect event and updating a variable)
I would like to use isConnected alike variable to check before getting an conn_error.

Or should I use a better approach ?
Thanks in advance for the feedback

I’m in the same situation.
I don’t know how to check if a connection is still active using the driver v4.
Any of you @Anton_Tonchev or @Guillermo_Lo_Coco found out a way to solve this?

Thank you in advance.

I still did not solve it. Lets see

const { MongoClient } = require(‘mongodb’)
const db = { connected: false }

db.client = new MongoClient(‘mongodb+srv://user:pass@server/?retryWrites=true&writeConcern=majority’)
db.client.on(‘open’, _=>{ db.connected=true, log(now()+‘DB connected.’) })
db.client.on(‘topologyClosed’, _=>{ db.connected=false, log(now()+‘DB disconnected.’) })

I am using this.

1 Like

Thank you @Guillermo_Lo_Coco. :slight_smile:
I’ve found this 2 links related to the removal of the client.isConnected()and how it now works. From what I could understand, the connection/reconnection is now practically managed internally for every operation, so there is no need to try to reconnect manually.

clicking on the “list here” text points to a link about the Unified Topology Design that explains the reasoning behind the removal of many 3.x commands. Here is the relevant section in my opinion:

I was using code like this for reusing connection from AWS Lambda, as recommended from MongoDB doc called “Best Practices Connecting From AWS Lambda” (http:// docs . atlas . mongodb . com/best-practices-connecting-from-aws-lambda/ sorry, I can’t post more than 2 links per post so… :stuck_out_tongue: ):

let cachedDb: Db;
let client: MongoClient;

export const connectToDatabase = async () => {
  
  if (cachedDb && client?.isConnected()) {
    console.log("Existing cached connection found!");
    return cachedDb;
  }
  console.log("Aquiring new DB connection....");
  try {
    // Connect to our MongoDB database hosted on MongoDB Atlas

    client = await MongoClient.connect(MONGODB_URI, {
      useNewUrlParser: true,
      useUnifiedTopology: true,      
    });

    // Specify which database we want to use
    const db = await client.db(DB_NAME);

    cachedDb = db;
    return db;
  } catch (error) {
    console.log("ERROR aquiring DB Connection!");
    console.log(error);
    throw error;
  }
};

But after reading the referenced links I changed it to something like this:

let cachedDb: Db;
let client: MongoClient;

export const connectToDatabase = async () => {
  
  if (cachedDb) {
    console.log("Existing cached connection found!");
    return cachedDb;
  }
  console.log("Aquiring new DB connection....");
  try {
    // Connect to our MongoDB database hosted on MongoDB Atlas

    client = await MongoClient.connect(MONGODB_URI);

    // Specify which database we want to use
    const db = await client.db(DB_NAME);

    cachedDb = db;
    return db;
  } catch (error) {
    console.log("ERROR aquiring DB Connection!");
    console.log(error);
    throw error;
  }
};

Hope it helps anyone trying to know about alternatives or why the commands were removed.

1 Like

@Ricardo_Montoya so basically, you just ignore the isConnected, assuming that it will be always true? I kind a suspected that this would be also the case. But I am still not sure especially if you have a pool and want to know which clients can still be reused, or need to be destroyed.

The solution of @Guillermo_Lo_Coco looks nice. I think we can even attack to the client an isConnected boolean in the client event listener, this would do perfectly the job.

1 Like

Always on the lookout for modern javascript syntax, I was puzzled about the above lines.
After a quick web search and pasting into Runkit and onto the command line REPL, I realized those lines are not new and improved code, but rather incorrect syntax which generates error message Uncaught SyntaxError: Unexpected token ':', I suspect what was intended was a comma instead of a colon, as follows.

let cachedDb, Db;
let client, MongoClient;

Noted for those who might spend time on it like I did …

Sorry @Joe_Devlin , I didn’t mention it was Typescript code.

2 Likes

A post was split to a new topic: Connection errors after upgrading to MongoDB v4 Node.js driver