Tryign to do homework "create an API route that returns a single movie based on a user provided id?"

Hello, I’m trying to finish the

“# How to Integrate MongoDB Into Your Next.js App” tutorial

The part I’m stuck on is

We can add additional API routes by creating additional files in the api directory. As a homework exercise, why don’t you create an API route that returns a single movie based on a user provided id?

My code looks like this

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



export default async (req, res) => {
  const client = await clientPromise;

  const { the_id } = req.query
  // console.log('hello hand')
  console.log(the_id)

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

  res.json(movies);
};

I don’t get how i would query the _id and return the movie the corresponds.

Would love any help, sorry if i posted in the wrong spot.

Thanks

I was able to display a movie by id# by creating a new new file, pages/api/[movieId].js

I used mongoose to do the following:

import { connectToDatabase } from "../../util/mongodb";
const mongoose = require('mongoose');

export default async (req, res) => {
  const { db } = await connectToDatabase();
  const objectId = mongoose.Types.ObjectId(req.query.movieId);


  const movie = await db
    .collection("movies")
    .findOne({ _id: objectId })
  res.json(movie);
};

I used the convo log to see what the value of “req” and “req.query” were, and that was helpful so that I could see that the data was coming through, I just had to get all the syntax right. There are definitely other ways to do this, but mongoose is nice.

Okay, that was yesterday. This is today. I figured it out sans mongoose, quite a bit simpler. I used the template literal to make it a string, there’s other ways to do that too.

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

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

  
  const movie = await db
    .collection("movies")
    .findOne( { "_id" : ObjectId(id) } )
  res.json(movie);
};
1 Like