🎓 A1Learner
🔍
0 of 50 lessons completed

Route Parameters for One Note

A route parameter is a named part of a path. It lets one route serve many addresses, one per value.

A route with a parameter

The colon marks the changing part.

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

Reading the parameter

req.params holds the value from the path.

const note = await Note.findById(req.params.id);

The value is a string

The id arrives as text, and findById accepts it.

const id = req.params.id;

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);
  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 first = await fetch(`${base}/api/notes/${ship._id}`);
console.log(await first.text());
const book = await Note.findOne({ title: 'Read a book' });
const second = await fetch(`${base}/api/notes/${book._id}`);
console.log(await second.text());
server.close();
await mongoose.disconnect();

Key points

  • A colon in a path marks a parameter, such as :id.
  • The parameter takes the matching part of the real path.
  • req.params holds the values, keyed by name.
  • findById reads one document by its id.
  • One route serves every note, because the id changes.

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 reads the id from req.params and finds that note. The script asks for two notes by id, one after the other. Each printed line is the JSON body of one answer.

Note

The id comes from the path, never from the body.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does :id mean in /api/notes/:id?