The Example the MongoDB Documentation Leaves Out

Jon Bell
2 min readJan 22, 2023

If you’re reading through the Mongo docs called How to Integrate MongoDB Into Your Next.js App, there’s a moment where they challenge you to work out the next bit on your own. Here’s the code you want to write:

import clientPromise from "../../../lib/mongodb";
import { ObjectId } from "mongodb";

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

try {
const client = await clientPromise;
const db = client.db("sample_mflix");
const movies = await db
.collection("movies")
.find({ _id: ObjectId(id) })
.toArray();

res.json(movies);
} catch (e) {
console.error(e);
}
};

And you’d put that in a file called /pages/api/movie/[id].js.

For SEO reasons, I am going to copy/paste the homework challenge text to help other people who might hit this wall:

As a homework exercise, why don’t you create an API route that returns a single movie based on a user provided id?

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.

The problem with this is even searching Google, Stack Overflow, and other sources, it turns out a lot of people are confused by this. I wasn’t able to find a single answer, so here you go! I eventually cracked it by finding a Mongo cheat sheet.

Writing good documentation is hard, but it should never require someone to do homework to get core information. In this example, the docs explain how to return lots of things from the DB, but not one. So if you’re making a blog, the docs explain how to pull down every blog post but don’t explain how to load one. That’s bad content design.

If you want to add extra credit into your docs, that’s awesome. But a) it should be for more advanced topics, not 101-level stuff and b) you should have a way to navigate to the solution. Encouragement to go to your community forum isn’t helpful. Documentation should teach, not punt.

--

--

Jon Bell

Designer, writer, teacher. I love building things.