Typed CRUD

Update one owned note

Use a narrow WHERE clause and returned rows so an update proves both ownership and whether a matching record existed.

8 minute lesson

~~~

The most expensive missing line in an update is often where(). Without it, every row can change.

For user-owned data, include both the note ID and trusted author ID in the condition. Do not load the row, check ownership, and update later when one conditional statement can keep that decision atomic.

const [updated] = await db
  .update(notes)
  .set({ title: 'A better title' })
  .where(and(eq(notes.id, noteId), eq(notes.authorId, userId)))
  .returning()

When updated is undefined, the note may be missing or belong to another user. Returning the same public result for both cases avoids revealing another user’s object existence.

Drizzle prevents many column mistakes, but it cannot know whether userId came from a verified session or an untrusted request body. Authorization still belongs to the application boundary.

Update a note as its owner, another signed-in user, and an unknown ID. Save the returned rows and final database state, then add a test that would fail if the ownership condition disappeared.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →