IsConnected not a function in next.js app

I’m starting to use the mongodb driver for next.js. I followed the example of How to Integrate MongoDB Into Your Next.js App | MongoDB but first I found that the example code doesn’t work anymore but I manage to make it work with a few tweaks.

Now I want to use it in my own app, so I went and npm install mongodb and everything is working, I can query the database and get the results, but the weird thing is the function isConnected is not working. I get a message saying: “TypeError: client.isConnected is not a function”.

I’m new with next.js and mongodb, so I don’t get what is happening, in the demo app with the example the function works without problems, but in my app I get this message.

Can somebody help me how to make it work? This is the line with the error:

const isConnected = await client.isConnected()

Thanks everybody.

1 Like

Hey Alejandro -

We just pushed a huge update to the next.js repo that changes how a couple of things work, so the issue is def NOT on your end. You’ll just have to make a few minor tweaks.

The updated code is here:

But essentially, the way we import the library has changed.

Instead of importing

import { connectToDatabase } from '../lib/mongodb'

and calling

const { client } = await connectToDatabase()

To get our connection to the database. We’ll instead import the library like so:

import clientPromise from '../lib/mongodb'

and to access a database in our getServerSideProps, we’ll do:

const client = await clientPromise

and now the client.isConnected() function should work.

The updated library itself looks like this:

import { MongoClient } from 'mongodb'

const uri = process.env.MONGODB_URI
const options = {
  useUnifiedTopology: true,
  useNewUrlParser: true,
}

let client
let clientPromise

if (!process.env.MONGODB_URI) {
  throw new Error('Please add your Mongo URI to .env.local')
}

if (process.env.NODE_ENV === 'development') {
  // In development mode, use a global variable so that the value
  // is preserved across module reloads caused by HMR (Hot Module Replacement).
  if (!global._mongoClientPromise) {
    client = new MongoClient(uri, options)
    global._mongoClientPromise = client.connect()
  }
  clientPromise = global._mongoClientPromise
} else {
  // In production mode, it's best to not use a global variable.
  client = new MongoClient(uri, options)
  clientPromise = client.connect()
}

// Export a module-scoped MongoClient promise. By doing this in a
// separate module, the client can be shared across functions.
export default clientPromise

I would check out the code here for further instructions:
https://github.com/vercel/next.js/blob/canary/examples/with-mongodb/pages/index.js

Please let me know if that helps! I will update the blog post in the next few days as well to reflect these changes.

Thanks!

  • Ado
2 Likes

Thanks for your help Ado, sadly I still get the error that IsConnected is not a function. If I take out the app is connecting and querying the DB without problem.

2 Likes

Yes, I have same problem with Alejandro even though I followed exact code as posted. I hope it will be notified by more developers and be fixed soon.

1 Like

In the Next.js example, they used mongodb@^3.5.9.

mongo@latest, which is 4.1.1 as of today, does not have isConnected method on MongoClient as far as I see. So if you just installed mongo in your own project, this might be it.

1 Like

Well it’s nice to know I’m not the only one having problems with the isConnected not being a function.

thanks and do you know an alternative to this function?

to solve the “isConnected is not a function” error, change the function getServerSideProps to:

export async function getServerSideProps(context) {

  let isConnected;
  try {
    const client = await clientPromise
    isConnected = true;
  } catch(e) {
    console.log(e);
    isConnected = false;
  }

  return {
    props: { isConnected },
  }
}

Thanks,
Rafael,

4 Likes

But how I create /api routing for api calls? I need to create API routes inside /page directory, but it will not accept mongodb.js. Can you share the code of API call, please?

This is how I’m calling my api routes:

import clientPromise from "../../../lib/mongodb";
export default async (req, res) => {
    const client = await clientPromise
    const { fieldvalue } = req.query
    const database = client.db('databasename');
    const userdb = await database.collection('collectionname')
      .find({ "<field>": `${ fieldvalue }` })
      .project({ "_id": 0 })
      .toArray();
  res.json(userdb)
}
2 Likes

For that problem, the standard solution is to import clientPromise because versions higher than 3.9/4.0 do not have "import {Mongoclient} " command.

Then also, if you want to use {MongoClient} then,

  1. stop the current running server
  2. Type ‘npm i mongodb@3.5.9’ in terminal
  3. Restart your server by ‘npm/yarn run dev’

Now it will work

Hi,
Is there a special reason that we export clientPromise? If I export it, I need to access to db object and pick the database I want to work with in each route. So I don’t want to repeat myself. Of course I can find a quick solution, before spending time I just wanted to learn what is the reason we do it like that.
Thanks