Next.js Dynamic Routes Returning Empty Array

Hello!
I’m following along in this tutorial (https://www.mongodb.com/how-to/nextjs-with-mongodb/), and am on the section about creating dynamic routes with Next.js. (Link to Next.js dynamic routes guide)

I have the initial route to get 20 movie objects from the db, and that works perfectly. The route lives at pages/api/movies and here’s the code I’m using for that:

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

export default async (req, res) => {
  const { db } = await connectToDatabase();

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

  res.json(movies);
};

Trouble is when I try to return a single movie object using a dynamic route in Next. The route is pages/api/movies/[id], and the code I have looks like this:

import { connectToDatabase } from '../../../util/mongodb';

export default async (req, res) => {
  const { db } = await connectToDatabase();
  const { id } = req.query;

  const movies = await db
    .collection("movies")
    .find({"_id": `${id}` })
    .limit(20)
    .toArray();

  res.json(movies);
};

But when I query the route with http://localhost:3000/api/movies/573a1394f29313caabcdfa3e I get back an empty array, even though it should correspond with this object:

"_id": "573a1394f29313caabcdfa3e",
"fullplot": "Some text"

Any help sorting this out is appreciated! Thanks in advance.

Hello @Zac_Alexander, welcome to the MongoDB Community forum!

In the route you are specifying a string “573a1394f29313caabcdfa3e”. But, you are querying the collection by its _id field - which I think is of type ObjectId. So, build the ObjectId using the input string and then use it in the query filter.

You can use the NodeJS Driver APIs ObjectID class for constructing the ObjectId using the string.

To give you some pointers, you’ll use Next.js Dynamic API Routes to capture the id . So if a user calls http://localhost:3000/api/movies/573a1394f29313caabcdfa3e the movie that should be returned is Seven Samurai . Another tip, the _id property for the sample_mflix database in MongoDB is stored as an ObjectID, so you’ll have to convert the string to an ObjectID. If you get stuck, create a thread on the MongoDB Community forums and we’ll solve it together! Next, we’ll take a look at how to access our MongoDB data within our Next.js pages.

MongoDB shouldn’t redirect people to something they didn’t even have a docu for.

it’s a line a mine on a perfect road.