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.