Cannot connect to MongoDB using Next.js tutorial

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