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.