Menu
CoddyTech

Collections and Databases

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

A database can contain several collections. Our shelf database has books and authors. A book document belongs in books; an author document belongs in authors. Choosing a collection does not read its documents yet.

const books = db.collection('books');
const authors = db.collection('authors');

The db variable represents the database. collection returns an object you can use to work with one named collection. Here the reading function is provided. Choose which collection it should read, then inspect the response and Data tab. The next step shows where db comes from.

challenge icon

Challenge

Easy

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

Change the selected collection to authors. Keep the supplied read call. Run and GET /result: you should see Frank Herbert and Jane Austen, with their born years. Selecting books instead would return book documents.

Try it yourself

export async function exercise(db) {
    const selected = db.collection('books');
    return selected.find().toArray();
}

All lessons in Databases with MongoDB

Practice on your own: Express playground