I’m working on a Node.js/Express backend using PostgreSQL (Neon serverless), TypeScript, and Zod for validation. I have a Students table with columns:
id UUID PRIMARY KEY,
firstName TEXT NOT NULL,
lastName TEXT NOT NULL,
email TEXT UNIQUE NOT NULL,
courseId UUID NOT NULL
I defined the following Zod schema for partial updates:
const updateSchema = z.object({
firstName: z.string(),
lastName: z.string(),
email: z.string(),
courseId: z.uuid(),
}).partial();
In my controller, I want to update only the fields provided in the request body. For example:
PATCH /students/10with body{ firstName: "John" }→ only updatesfirstName.PATCH /students/10with body{ email: "[email protected]", courseId: "uuid-123" }→ updatesemailandcourseId.
Currently, my update query looks like this:
await sql`
UPDATE Students
SET firstName = ${fields.firstName},
lastName = ${fields.lastName},
email = ${fields.email},
courseId = ${fields.courseId}
WHERE id = ${id}
RETURNING *;
`;
But this always tries to update all fields, even if they’re null or not provided in the request body.
the sql is coming from
import { neon } from "@neondatabase/serverless";
const sql=neon(
`postgresql://${PGUSER}:${PGPASSWORD}@${PGHOST}/${PGDATABASE}?sslmode=require&channel_binding=require`
);
How can I use Neon to dynamically construct the SET clause in PostgreSQL so that just the supplied (non-null/non-undefined) fields are updated?
sqlinawait sqlUPDATE Students ...` coming from?