Cannot connect to MongoDB using Next.js tutorial

Hi all, I’m new to MongoDB and Next.js and am following the MongoDB Next.js integration tutorial working in the project cloned from this example repo.

I am able to get everything in the example repo to work properly, with isConnected to return true from this snippet in /pages/index.js:

export async function getServerSideProps(context) {
  try {
    await clientPromise
    return {
      props: { isConnected: true },
    }
  } catch (e) {
    console.error(e)
    return {
      props: { isConnected: false },
    }
  }
}

`
Then I added an API endpoint at /pages/api/test.js like so:

import { clientPromise } from "../../util/mongodb";

export default async (req, res) => {
  const client = await clientPromise
  const db = client.db('sample_mflix')

  const movies = db
    .collection("movies")
    .find({})
    .sort({ metacritic: -1 })
    .limit(20)
    .toArray();

  res.json(movies);
}

This is the exact same code as provided in the tutorial except that I am importing and using clientPromise instead of connectToDatabase due to updates to the mongodb.js utility file since the tutorial was originally posted. When I try and access the endpoint at localhost:3000/api/test, I get TypeError: Cannot read property 'db' of undefined on the line const db = client.db('sample_mflix').

It seems like clientPromise is returning undefined but I cannot figure out why. Can someone help me understand? Thanks so much.

Hi :wave: @amy,

Welcome to MongoDB Community forums :sparkles:

Due to some recent changes in Next.js, the article needs some revision. Although here you go:

So, first, you need to modify

to :point_down:

import clientPromise from "../../util/mongodb";

without curly parenthesis as stated here

And then the following code is as follows: :point_down:

import clientPromise from "../../util/mongodb";

export default async (req, res) => {
    try {
        const client = await clientPromise;
        const db = client.db("sample_mflix");

        const movies = await db
          .collection("movies")
          .find({})
          .sort({ metacritic: -1 })
          .limit(10)
          .toArray();

        res.status(200).json(movies);
    } catch (error) {
        console.log(error);
    }
}

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

Best,
Kushagra Kesav

3 Likes

Thank you! This solved my problem :slight_smile:

1 Like

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