Menu
CoddyTech

Finding One Document

Part of the Databases with MongoDB section of Coddy's Node.js journey. Lesson 6 of 29.

Sometimes you need one document rather than the whole collection. findOne takes a filter object. Its field names and values describe the document to look for.

const book = await books.findOne({title: 'Dune'});
// one book document, not an array

The title value must match. When no document matches, findOne returns null. Check for that before reading fields from the result. This step uses a title you can read. The following lesson introduces generated ids and how their type differs from the text in a URL.

challenge icon

Challenge

Easy

This is a small practice project. Its setup is provided; edit only exercise.js.

Find Emma by title and return the document. Run and GET /result: title is Emma and year is 1815. Use findOne, so the result is a single object rather than a list.

Try it yourself

export async function exercise(books) {
    return {};
}

All lessons in Databases with MongoDB

Practice on your own: Express playground