While working on FocusYar, my Next.js project, I had a confusing issue: a goal existed in the database, but the application couldn't retrieve it correctly.
The problem was a type mismatch.
I was working with an ID that arrived as a string, while my Zod schema expected a number.
Before
const id = "123";
The Fix
import { z } from "zod";
const schema = z.object({
id: z.coerce.number(),
});
z.coerce.number() attempts to convert the input to a number before validation.
This is especially useful when handling URL parameters and query strings.
A More Strict Version
If the ID must be a positive integer, I can validate that requirement too:
const schema = z.object({
id: z.coerce.number().int().positive(),
});
One important detail: coercion and validation are different things. Converting a value to a number doesn't automatically make it a valid ID.
My Takeaway
When debugging a problem, I shouldn't immediately assume the database or query is broken. I should inspect the data, check its type, and follow it through the application.
I'm learning to solve problems by understanding their causes instead of just fixing their symptoms.
Top comments (0)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.