🎓 A1Learner
🔍
0 of 50 lessons completed

The Notes API: Getting One Note

A single-note route is a route that returns one note by id. It reads the id from the path and looks the note up.

Finding one note

The route looks the note up by id.

app.get('/api/notes/:id', async (req, res) => {
  const note = await Note.findById(req.params.id);
  res.json({ title: note.title, done: note.done });
});

A missing note

No note means a 404 answer.

if (!note) {
  res.status(404).json({ error: 'Note not found' });
  return;
}

One note, one body

The route sends only the two fields.

res.json({ title: note.title, done: note.done });

Example

import express from 'express';
import mongoose from 'mongoose';

await mongoose.connect('mongodb://localhost:27017/notes');
const noteSchema = new mongoose.Schema({ title: String, done: Boolean });
const Note = mongoose.model('Note', noteSchema);
await Note.create({ title: 'Buy milk', done: false });
await Note.create({ title: 'Ship MERN', done: true });
await Note.create({ title: 'Read a book', done: false });
const app = express();
app.get('/api/notes/:id', async (req, res) => {
  const note = await Note.findById(req.params.id);
  if (!note) {
    res.status(404).json({ error: 'Note not found' });
    return;
  }
  res.json({ title: note.title, done: note.done });
});
const server = app.listen(0);
const port = server.address().port;
const base = `http://localhost:${port}`;
const ship = await Note.findOne({ title: 'Ship MERN' });
const found = await fetch(`${base}/api/notes/${ship._id}`);
console.log(await found.text());
const missingId = new mongoose.Types.ObjectId();
const gone = await fetch(`${base}/api/notes/${missingId}`);
console.log(gone.status);
console.log(await gone.text());
server.close();
await mongoose.disconnect();

Key points

  • GET /api/notes/:id returns a single note.
  • findById looks the note up by the id in the path.
  • A missing id answers 404 with a short error message.
  • The error body names the problem in plain words.

In this example, the script connects to the notes database and saves the three notes. It builds an Express app with one route, GET /api/notes/:id. The route finds the note by id and sends back its title and done fields. When the id matches nothing, it answers 404 with an error message. The script asks for one real note, then for one that does not exist. The first line is the note, and the next two lines are the 404 code and its body.

Note

The caller checks the code before it trusts the body.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does GET /api/notes/:id return when the id is missing?