client.isConnected is not a function error

I was following the tutorial Building Modern Applications with Next.js and MongoDB | MongoDB but get an internal server error 500 when calling the api to mongoDB. Upon further investigation, I found that the response from the api call was ‘client.isConnected is not a function’.

After doing some searching, I think the most likely reason is that the code in the tutorial is outdated hence it gives an error. I modified this part of the code according to something I saw from my searching and it seems to work.

async function database(req, res, next) {
  // original code
  // if (!client.isConnected()) await client.connect();
  // modified code: to not check for client.isConnected
  await client.connect();
  req.dbClient = client;
  req.db = client.db('MCT');
  return next();
}

I removed the condition checking for client.isConnected as I read it may not be needed anymore, but I’m not sure about this so I was wondering if this is the correct approach and if not, what can I do to solve this issue? Thanks in advance.

Hi @Yi_Jiun_Tay,

The legacy MongoClient.isConnected method was removed in version 4 of the MongoDB Node.js Driver (see NODE-2317).

Good catch!

Update - We’ve updated the article at Building Modern Applications with Next.js and MongoDB | MongoDB to remove the incorrect line of code :slight_smile:

1 Like

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