“# 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?
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);
};