IsConnected not a function in next.js app

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