Module 3 · Build real CRUD features
3.3 Edit, move and delete issues
Complete the issue lifecycle with an edit form shared with create, a status field, a UTC date-time input, updated timestamps, and delete.
Starting point
Issues can be listed, viewed and created. The creation time is always "now", the status is always open, and nothing can be changed afterwards.
Outcome
/issues/101/editedits title, description, building, priority, status and the time it occurred.POST /issues/101/deletedeletes the issue (after a confirmation in the browser).- The create and edit forms are one template,
views/issues/form.ejs. updated_atchanges on every edit; the issue page shows it.
The problem
Real maintenance issues change after they are reported: someone investigates (open → investigating), closes them, corrects the title, or discovers that the issue happened at another building. The form needs those fields, and the validation needs to know the difference between creating (status starts as open) and editing (status can change).
There is a smaller problem with time. <input type="datetime-local"> sends a value such as 2026-11-02T09:15 with no time zone. We must decide what it means. We store and display UTC everywhere (lesson 1.4), so the form is UTC too, and says so.
Build it
1. Data access
Change createIssue to accept the time it occurred, and add update and delete in src/models/issues.js:
export async function createIssue({ building_id, title, description, priority }) {export async function createIssue({ building_id, title, description, priority, occurred_at }) { const { rows } = await query( `INSERT INTO issues (building_id, title, description, priority, occurred_at) VALUES ($1, $2, $3, $4, now()) VALUES ($1, $2, $3, $4, $5) RETURNING id`, [building_id, title, description, priority], [building_id, title, description, priority, occurred_at], ); return rows[0];} export async function updateIssue(id, { building_id, title, description, priority, status, occurred_at }) { const { rows } = await query( `UPDATE issues SET building_id = $2, title = $3, description = $4, priority = $5, status = $6, occurred_at = $7, updated_at = now() WHERE id = $1 RETURNING id`, [id, building_id, title, description, priority, status, occurred_at], ); return rows[0] ?? null;} export async function deleteIssue(id) { const { rowCount } = await query('DELETE FROM issues WHERE id = $1', [id]); return rowCount === 1;}
Show the whole src/models/issues.js after this change
import { query } from '../db.js'; const ISSUE_COLUMNS = ` e.id, e.building_id, s.name AS building_name, s.organisation_id, e.title, e.description, e.priority, e.status, e.occurred_at, e.created_at, e.updated_at`; export async function listIssues() { const { rows } = await query( `SELECT ${ISSUE_COLUMNS} FROM issues e JOIN buildings s ON s.id = e.building_id ORDER BY e.occurred_at DESC, e.id DESC LIMIT 50`, ); return rows;} export async function listRecentIssuesForBuilding(buildingId, limit = 10) { const { rows } = await query( `SELECT ${ISSUE_COLUMNS} FROM issues e JOIN buildings s ON s.id = e.building_id WHERE e.building_id = $1 ORDER BY e.occurred_at DESC, e.id DESC LIMIT $2`, [buildingId, limit], ); return rows;} export async function findIssue(id) { const { rows } = await query( `SELECT ${ISSUE_COLUMNS} FROM issues e JOIN buildings s ON s.id = e.building_id WHERE e.id = $1`, [id], ); return rows[0] ?? null;} export async function createIssue({ building_id, title, description, priority, occurred_at }) { const { rows } = await query( `INSERT INTO issues (building_id, title, description, priority, occurred_at) VALUES ($1, $2, $3, $4, $5) RETURNING id`, [building_id, title, description, priority, occurred_at], ); return rows[0];} export async function updateIssue(id, { building_id, title, description, priority, status, occurred_at }) { const { rows } = await query( `UPDATE issues SET building_id = $2, title = $3, description = $4, priority = $5, status = $6, occurred_at = $7, updated_at = now() WHERE id = $1 RETURNING id`, [id, building_id, title, description, priority, status, occurred_at], ); return rows[0] ?? null;} export async function deleteIssue(id) { const { rowCount } = await query('DELETE FROM issues WHERE id = $1', [id]); return rowCount === 1;}import { query } from '../db.js';
const ISSUE_COLUMNS = `
e.id, e.building_id, s.name AS building_name, s.organisation_id,
e.title, e.description, e.priority, e.status,
e.occurred_at, e.created_at, e.updated_at`;
export async function listIssues() {
const { rows } = await query(
`SELECT ${ISSUE_COLUMNS}
FROM issues e
JOIN buildings s ON s.id = e.building_id
ORDER BY e.occurred_at DESC, e.id DESC
LIMIT 50`,
);
return rows;
}
export async function listRecentIssuesForBuilding(buildingId, limit = 10) {
const { rows } = await query(
`SELECT ${ISSUE_COLUMNS}
FROM issues e
JOIN buildings s ON s.id = e.building_id
WHERE e.building_id = $1
ORDER BY e.occurred_at DESC, e.id DESC
LIMIT $2`,
[buildingId, limit],
);
return rows;
}
export async function findIssue(id) {
const { rows } = await query(
`SELECT ${ISSUE_COLUMNS}
FROM issues e
JOIN buildings s ON s.id = e.building_id
WHERE e.id = $1`,
[id],
);
return rows[0] ?? null;
}
export async function createIssue({ building_id, title, description, priority, occurred_at }) {
const { rows } = await query(
`INSERT INTO issues (building_id, title, description, priority, occurred_at)
VALUES ($1, $2, $3, $4, $5)
RETURNING id`,
[building_id, title, description, priority, occurred_at],
);
return rows[0];
}
export async function updateIssue(id, { building_id, title, description, priority, status, occurred_at }) {
const { rows } = await query(
`UPDATE issues
SET building_id = $2, title = $3, description = $4, priority = $5, status = $6, occurred_at = $7, updated_at = now()
WHERE id = $1
RETURNING id`,
[id, building_id, title, description, priority, status, occurred_at],
);
return rows[0] ?? null;
}
export async function deleteIssue(id) {
const { rowCount } = await query('DELETE FROM issues WHERE id = $1', [id]);
return rowCount === 1;
}
occurred_at arrives as a JavaScript Date. pg sends it to PostgreSQL as an ISO timestamp with time zone, so no conversion is needed.
2. One form for create and edit
Rename the template with Git, then replace its content:
git mv views/issues/new.ejs views/issues/form.ejs
<%- include('../partials/head') %><h1><%= title %></h1> <% if (Object.keys(errors).length > 0) { %> <div class="error-summary" role="alert"> <p>Please fix the highlighted fields.</p> </div><% } %> <form method="post" action="<%= action %>" class="form" novalidate> <div class="field<%= errors.title ? ' has-error' : '' %>"> <label for="title">Title</label> <input id="title" name="title" value="<%= values.title ?? '' %>" maxlength="200" required> <% if (errors.title) { %><p class="field-error"><%= errors.title %></p><% } %> </div> <div class="field<%= errors.building_id ? ' has-error' : '' %>"> <label for="building_id">Building</label> <select id="building_id" name="building_id"> <option value="">Choose…</option> <% for (const building of buildings) { %> <option value="<%= building.id %>"<%= values.building_id === building.id ? ' selected' : '' %>><%= building.organisation_name %> · <%= building.name %></option> <% } %> </select> <% if (errors.building_id) { %><p class="field-error"><%= errors.building_id %></p><% } %> </div> <div class="field<%= errors.occurred_at ? ' has-error' : '' %>"> <label for="occurred_at">Occurred at (UTC)</label> <input id="occurred_at" name="occurred_at" type="datetime-local" value="<%= values.occurred_at ?? '' %>"> <% if (errors.occurred_at) { %><p class="field-error"><%= errors.occurred_at %></p><% } %> </div> <div class="field<%= errors.description ? ' has-error' : '' %>"> <label for="description">Description <span class="muted">(optional)</span></label> <textarea id="description" name="description" maxlength="2000"><%= values.description ?? '' %></textarea> <% if (errors.description) { %><p class="field-error"><%= errors.description %></p><% } %> </div> <div class="field<%= errors.priority ? ' has-error' : '' %>"> <label for="priority">Priority</label> <select id="priority" name="priority"> <option value="">Choose…</option> <% for (const s of priorities) { %> <option value="<%= s %>"<%= values.priority === s ? ' selected' : '' %>><%= s %></option> <% } %> </select> <% if (errors.priority) { %><p class="field-error"><%= errors.priority %></p><% } %> </div> <% if (issue) { %> <div class="field<%= errors.status ? ' has-error' : '' %>"> <label for="status">Status</label> <select id="status" name="status"> <% for (const s of statuses) { %> <option value="<%= s %>"<%= values.status === s ? ' selected' : '' %>><%= s %></option> <% } %> </select> <% if (errors.status) { %><p class="field-error"><%= errors.status %></p><% } %> </div> <% } %> <div class="form-actions"> <button type="submit" class="btn btn-primary"><%= issue ? 'Save changes' : 'Save issue' %></button> <a class="btn" href="<%= issue ? `/issues/${issue.id}` : '/issues' %>">Cancel</a> </div></form><%- include('../partials/foot') %>Compared with the old new.ejs: the heading and action come from the route, there is an "Occurred at (UTC)" field, and the status field appears only when editing.
3. The issues router
The validation, the form helper and three new routes change this file substantially. Replace it; new and changed lines are highlighted:
import express from 'express';import { listIssues, findIssue, createIssue, updateIssue, deleteIssue } from '../models/issues.js';import { listBuildings } from '../models/buildings.js';import { PG_ERRORS } from '../db.js';import { parseId } from '../lib/ids.js';import { cleanText } from '../lib/validation.js'; export const issuesRouter = express.Router(); export const PRIORITIES = ['low', 'medium', 'high', 'critical'];export const STATUSES = ['open', 'investigating', 'closed'];const FIVE_MINUTES = 5 * 60 * 1000; // <input type="datetime-local"> sends "2026-11-02T09:15" without a time zone. We treat it as UTC.function parseDateTimeLocal(value) { if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/.test(value)) { return null; } const date = new Date(`${value}:00Z`); return Number.isNaN(date.getTime()) ? null : date;} // The reverse: a Date as "YYYY-MM-DDTHH:MM" in UTC, for the input's value attribute.function toDateTimeLocal(date) { return new Date(date).toISOString().slice(0, 16);} function validateIssue(input, { editing }) { const errors = {}; const title = cleanText(input.title, { min: 3, max: 200 }); const description = cleanText(input.description, { max: 2000 }); const buildingId = parseId(input.building_id); const occurredAt = parseDateTimeLocal(input.occurred_at); const status = editing ? input.status : 'open'; if (!title.ok) { errors.title = 'Title must be between 3 and 200 characters.'; } if (!description.ok) { errors.description = 'Description must be at most 2000 characters.'; } if (!PRIORITIES.includes(input.priority)) { errors.priority = `Priority must be one of: ${PRIORITIES.join(', ')}.`; } if (buildingId === null) { errors.building_id = 'Choose a building.'; } if (!occurredAt) { errors.occurred_at = 'Enter the date and time it happened (UTC).'; } else if (occurredAt.getTime() > Date.now() + FIVE_MINUTES) { errors.occurred_at = 'That time is in the future.'; } if (!STATUSES.includes(status)) { errors.status = `Status must be one of: ${STATUSES.join(', ')}.`; } // values: what the form shows again. record: what we store. const values = { title: title.text, description: description.text, priority: input.priority, building_id: buildingId, status, occurred_at: typeof input.occurred_at === 'string' ? input.occurred_at : '', }; const record = { ...values, occurred_at: occurredAt }; return { errors, values, record };} async function renderIssueForm(res, status, { issue = null, values = {}, errors = {} } = {}) { const buildings = await listBuildings(); res.status(status).render('issues/form', { title: issue ? `Edit issue #${issue.id}` : 'Report an issue', action: issue ? `/issues/${issue.id}/edit` : '/issues', issue, values, errors, buildings, priorities: PRIORITIES, statuses: STATUSES, });} async function loadIssue(req, res) { const id = parseId(req.params.id); const issue = id === null ? null : await findIssue(id); if (!issue) { res.status(404).render('not-found', { title: 'Not found', path: req.originalUrl }); return null; } return issue;} issuesRouter.get('/', async (req, res) => { const issues = await listIssues(); res.render('issues/index', { title: 'Maintenance issues', issues });}); issuesRouter.get('/new', async (req, res) => { await renderIssueForm(res, 200, { values: { occurred_at: toDateTimeLocal(new Date()) } });}); issuesRouter.post('/', async (req, res) => { const { errors, values, record } = validateIssue(req.body ?? {}, { editing: false }); if (Object.keys(errors).length > 0) { return renderIssueForm(res, 400, { values, errors }); } let created; try { created = await createIssue(record); } catch (err) { if (err.code === PG_ERRORS.FOREIGN_KEY_VIOLATION) { return renderIssueForm(res, 400, { values, errors: { building_id: 'Choose a building.' } }); } throw err; } res.redirect(303, `/issues/${created.id}`);}); issuesRouter.get('/:id', async (req, res) => { const issue = await loadIssue(req, res); if (!issue) return; res.render('issues/show', { title: issue.title, issue });}); issuesRouter.get('/:id/edit', async (req, res) => { const issue = await loadIssue(req, res); if (!issue) return; await renderIssueForm(res, 200, { issue, values: { ...issue, occurred_at: toDateTimeLocal(issue.occurred_at) } });}); issuesRouter.post('/:id/edit', async (req, res) => { const issue = await loadIssue(req, res); if (!issue) return; const { errors, values, record } = validateIssue(req.body ?? {}, { editing: true }); if (Object.keys(errors).length > 0) { return renderIssueForm(res, 400, { issue, values, errors }); } try { await updateIssue(issue.id, record); } catch (err) { if (err.code === PG_ERRORS.FOREIGN_KEY_VIOLATION) { return renderIssueForm(res, 400, { issue, values, errors: { building_id: 'Choose a building.' } }); } throw err; } res.redirect(303, `/issues/${issue.id}`);}); issuesRouter.post('/:id/delete', async (req, res) => { const issue = await loadIssue(req, res); if (!issue) return; await deleteIssue(issue.id); res.redirect(303, '/issues');});The important ideas:
valuesandrecord. The form needs the raw text the user typed ("2026-11-02T09:15") to show it again; the database needs aDate. Keeping them as two objects stops one from leaking into the other.- Status on create.
validateIssueignores anystatussent with a new issue; new issues are alwaysopen. On edit the status must be one of the allowed values. - The future check allows five minutes of clock difference between the browser and the server.
loadIssuefollows the same "find or 404" pattern as organisations and buildings.- Moving an issue is just changing
building_idin the edit form. Note it now; in Module 8 a move needs permission at both buildings.
4. Buttons on the issue page
<div class="page-header"> <h1><%= issue.title %></h1> <div class="actions"> <a class="btn" href="/issues/<%= issue.id %>/edit">Edit</a> <form method="post" action="/issues/<%= issue.id %>/delete" data-confirm="Delete this issue? This cannot be undone."> <button type="submit" class="btn btn-danger">Delete</button> </form> </div></div>
<dt>Occurred</dt><dd><%= formatDate(issue.occurred_at) %></dd> <dt>Occurred</dt><dd><%= formatDate(issue.occurred_at) %> UTC</dd> <dt>Last updated</dt><dd><%= formatDate(issue.updated_at) %> UTC</dd>
Show the whole views/issues/show.ejs after this change
<%- include('../partials/head') %><p class="breadcrumbs"><a href="/issues">Issues</a> / #<%= issue.id %></p><div class="page-header"> <h1><%= issue.title %></h1> <div class="actions"> <a class="btn" href="/issues/<%= issue.id %>/edit">Edit</a> <form method="post" action="/issues/<%= issue.id %>/delete" data-confirm="Delete this issue? This cannot be undone."> <button type="submit" class="btn btn-danger">Delete</button> </form> </div></div><dl class="details"> <dt>Building</dt><dd><%= issue.building_name %></dd> <dt>Priority</dt><dd><span class="badge sev-<%= issue.priority %>"><%= issue.priority %></span></dd> <dt>Status</dt><dd><span class="badge status-<%= issue.status %>"><%= issue.status %></span></dd> <dt>Occurred</dt><dd><%= formatDate(issue.occurred_at) %> UTC</dd> <dt>Last updated</dt><dd><%= formatDate(issue.updated_at) %> UTC</dd></dl><% if (issue.description) { %> <h2>Description</h2> <p class="prose"><%= issue.description %></p><% } %><%- include('../partials/foot') %><%- include('../partials/head') %>
<p class="breadcrumbs"><a href="/issues">Issues</a> / #<%= issue.id %></p>
<div class="page-header">
<h1><%= issue.title %></h1>
<div class="actions">
<a class="btn" href="/issues/<%= issue.id %>/edit">Edit</a>
<form method="post" action="/issues/<%= issue.id %>/delete" data-confirm="Delete this issue? This cannot be undone.">
<button type="submit" class="btn btn-danger">Delete</button>
</form>
</div>
</div>
<dl class="details">
<dt>Building</dt><dd><%= issue.building_name %></dd>
<dt>Priority</dt><dd><span class="badge sev-<%= issue.priority %>"><%= issue.priority %></span></dd>
<dt>Status</dt><dd><span class="badge status-<%= issue.status %>"><%= issue.status %></span></dd>
<dt>Occurred</dt><dd><%= formatDate(issue.occurred_at) %> UTC</dd>
<dt>Last updated</dt><dd><%= formatDate(issue.updated_at) %> UTC</dd>
</dl>
<% if (issue.description) { %>
<h2>Description</h2>
<p class="prose"><%= issue.description %></p>
<% } %>
<%- include('../partials/foot') %>
5. Update the tests
The form now requires occurred_at, so the existing tests must send it. Replace test/issues.test.js; the last four tests are new:
import { test, before, after } from 'node:test';import assert from 'node:assert/strict';import request from 'supertest';import { app } from '../src/app.js';import { pool } from '../src/db.js';import { resetDatabase } from './helpers.js'; before(resetDatabase);after(() => pool.end()); const validIssue = { title: 'Water leak by the staff entrance', building_id: '10', priority: 'low', occurred_at: '2026-11-20T10:30' }; test('GET /issues lists issues from the database', async () => { const res = await request(app).get('/issues'); assert.equal(res.status, 200); assert.match(res.text, /Lift stuck between floors 2 and 3/);}); test('GET /issues/101 shows one issue with its building', async () => { const res = await request(app).get('/issues/101'); assert.equal(res.status, 200); assert.match(res.text, /<h1>Lift stuck between floors 2 and 3<\/h1>/); assert.match(res.text, /Dublin Offices/);}); test('GET /issues/:id answers 404 for unknown or malformed ids', async () => { for (const id of ['999999', 'abc', '0', '99999999999']) { const res = await request(app).get(`/issues/${id}`); assert.equal(res.status, 404, `id ${id}`); }}); test('POST /issues re-renders the form with errors', async () => { const res = await request(app).post('/issues').type('form').send({ title: '', building_id: '', priority: '', occurred_at: '' }); assert.equal(res.status, 400); assert.match(res.text, /Choose a building/); assert.match(res.text, /Enter the date and time it happened/);}); test('POST /issues stores the issue and redirects to it', async () => { const res = await request(app).post('/issues').type('form').send(validIssue); assert.equal(res.status, 303); const page = await request(app).get(res.headers.location); assert.equal(page.status, 200); assert.match(page.text, /Water leak by the staff entrance/); assert.match(page.text, /20 Nov 2026, 10:30 UTC/);}); test('POST /issues with a building that does not exist is a form error, not a 500', async () => { const res = await request(app).post('/issues').type('form').send({ ...validIssue, building_id: '999' }); assert.equal(res.status, 400); assert.match(res.text, /Choose a building/);}); test('the stored row has the cleaned values and ignores a client-sent status', async () => { await request(app).post('/issues').type('form').send({ ...validIssue, title: ' Spaces around ', building_id: '20', status: 'closed' }); const { rows } = await pool.query("SELECT title, building_id, status FROM issues WHERE title = 'Spaces around'"); assert.deepEqual(rows, [{ title: 'Spaces around', building_id: 20, status: 'open' }]);}); test('an issue time in the future is rejected', async () => { const res = await request(app).post('/issues').type('form').send({ ...validIssue, occurred_at: '2099-01-01T00:00' }); assert.equal(res.status, 400); assert.match(res.text, /That time is in the future/);}); test('GET /issues/101/edit shows the current values', async () => { const res = await request(app).get('/issues/101/edit'); assert.equal(res.status, 200); assert.match(res.text, /value="2026-11-02T09:15"/); assert.match(res.text, /<option value="open" selected>open<\/option>/);}); test('POST /issues/:id/edit changes the status and updated_at', async () => { const before = (await pool.query('SELECT updated_at FROM issues WHERE id = 103')).rows[0].updated_at; const res = await request(app).post('/issues/103/edit').type('form') .send({ title: 'Front door lock sticks at entrance 4', building_id: '20', priority: 'medium', status: 'investigating', occurred_at: '2026-11-08T07:05' }); assert.equal(res.status, 303); const { rows } = await pool.query('SELECT status, updated_at FROM issues WHERE id = 103'); assert.equal(rows[0].status, 'investigating'); assert.ok(rows[0].updated_at > before);}); test('POST /issues/:id/delete removes the issue', async () => { const created = await request(app).post('/issues').type('form').send({ ...validIssue, title: 'Delete me please' }); const res = await request(app).post(`${created.headers.location}/delete`); assert.equal(res.status, 303); assert.equal((await request(app).get(created.headers.location)).status, 404);});Run and inspect
npm test
> caretaker@1.0.0 test
> node --env-file=.env.test --test --test-concurrency=1 --test-reporter=spec "test/**/*.test.js"
✔ a building can be created inside an organisation (56.474292ms)
✔ a duplicate building name in the same organisation is a field error (3.232125ms)
✔ the same building name is allowed in another organisation (8.24575ms)
✔ a building with issues cannot be deleted (22.27475ms)
✔ an empty building can be deleted (7.339083ms)
✔ an organisation with buildings cannot be deleted, an empty one can (15.045458ms)
✔ GET /issues lists issues from the database (69.774833ms)
✔ GET /issues/101 shows one issue with its building (3.747541ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (6.201125ms)
✔ POST /issues re-renders the form with errors (6.269667ms)
✔ POST /issues stores the issue and redirects to it (5.321583ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (8.998083ms)
✔ the stored row has the cleaned values and ignores a client-sent status (3.611917ms)
✔ an issue time in the future is rejected (1.885208ms)
✔ GET /issues/101/edit shows the current values (2.261542ms)
✔ POST /issues/:id/edit changes the status and updated_at (2.735834ms)
✔ POST /issues/:id/delete removes the issue (3.773375ms)
✔ GET /organisations lists organisations with building counts (55.36225ms)
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (3.45225ms)
✔ POST /organisations validates and creates (9.896083ms)
✔ POST /organisations/:id/edit renames the organisation (5.057875ms)
✔ unknown organisations are 404 (4.152834ms)
ℹ tests 22
ℹ suites 0
ℹ pass 22
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 603.506667
npm run dev
> caretaker@1.0.0 dev
> node --env-file=.env --watch src/server.js
Caretaker listening on http://localhost:3000

Change the status with a form post and look at the row:
curl -si http://localhost:3000/issues/104/edit --data-urlencode "title=Water stain on the ceiling of flat 7" --data-urlencode "building_id=20" --data-urlencode "priority=high" --data-urlencode "status=closed" --data-urlencode "occurred_at=2026-11-10T11:30" | head -1
HTTP/1.1 303 See Other
docker compose exec db psql -U caretaker caretaker, then paste the SQL.SELECT id, status, occurred_at, created_at < updated_at AS was_updated FROM issues WHERE id = 104;
id | status | occurred_at | was_updated
-----+--------+------------------------+-------------
104 | closed | 2026-11-10 11:30:00+00 | t
(1 row)Experiment
The form shows only the fields we chose, but a client can post anything.
created_at if a client adds created_at=2000-01-01 to the edit form post?curl -si http://localhost:3000/issues/104/edit --data-urlencode "title=Water stain on the ceiling of flat 7" --data-urlencode "building_id=20" --data-urlencode "priority=high" --data-urlencode "status=closed" --data-urlencode "occurred_at=2026-11-10T11:30" --data-urlencode "created_at=2000-01-01" | head -1
HTTP/1.1 303 See Other
docker compose exec db psql -U caretaker caretaker, then paste the SQL.SELECT id, created_at::date FROM issues WHERE id = 104;
id | created_at
-----+------------
104 | 2026-11-28
(1 row)Reveal Answer
Nothing. created_at keeps its original value, because updateIssue only writes the columns we listed, from the validated record. A design that copied req.body into the UPDATE ("mass assignment") would have let the client rewrite history, or, in later modules, change who reported an issue or which organisation it belongs to.
Checkpoint
npm test
> caretaker@1.0.0 test
> node --env-file=.env.test --test --test-concurrency=1 --test-reporter=spec "test/**/*.test.js"
✔ a building can be created inside an organisation (50.377875ms)
✔ a duplicate building name in the same organisation is a field error (2.952958ms)
✔ the same building name is allowed in another organisation (7.89625ms)
✔ a building with issues cannot be deleted (21.74975ms)
✔ an empty building can be deleted (6.834041ms)
✔ an organisation with buildings cannot be deleted, an empty one can (13.220458ms)
✔ GET /issues lists issues from the database (62.704834ms)
✔ GET /issues/101 shows one issue with its building (3.802708ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (6.65225ms)
✔ POST /issues re-renders the form with errors (6.412292ms)
✔ POST /issues stores the issue and redirects to it (5.516584ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (9.226458ms)
✔ the stored row has the cleaned values and ignores a client-sent status (3.103833ms)
✔ an issue time in the future is rejected (2.130458ms)
✔ GET /issues/101/edit shows the current values (2.394083ms)
✔ POST /issues/:id/edit changes the status and updated_at (2.78625ms)
✔ POST /issues/:id/delete removes the issue (26.236167ms)
✔ GET /organisations lists organisations with building counts (54.533375ms)
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (5.028458ms)
✔ POST /organisations validates and creates (12.594083ms)
✔ POST /organisations/:id/edit renames the organisation (6.834417ms)
✔ unknown organisations are 404 (4.260875ms)
ℹ tests 22
ℹ suites 0
ℹ pass 22
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 623.984166
git add -A
git commit -m "Edit, move and delete issues"
[main efee9ff] Edit, move and delete issues
5 files changed, 192 insertions(+), 36 deletions(-)
rename views/issues/{new.ejs => form.ejs} (64%)
Symptom The edit form shows the time one or more hours off
Something converted the time to your local time zone. toDateTimeLocal must use toISOString() (UTC), and parseDateTimeLocal must append Z.
Symptom Failed to lookup view "issues/new"
A route still renders issues/new. After the rename, every route renders issues/form.
Recap and next step
One template serves create and edit. Validation separates what the form shows (values) from what we store (record), ignores fields it does not know, and treats the date-time input as UTC. Updates set updated_at; deletes need no extra rule because issues have no children.
The issue list still shows a fixed 50 rows. Next we add pagination, sorting and filters, and meet the one place where values cannot be passed as $1.
Open the checkpoint files for lesson 3.3 (separate page; only files from this lesson and earlier)