delete
Remove records from your database
delete removes a single record matched by a unique identifier and returns it. It throws if the record doesn’t exist.
const user = await client.user.delete({
where: { id: "user_123" },
});
// Result: the deleted record
Options
await client.user.delete({
where: { ... }, // Required: unique identifier
select: { ... }, // Optional: fields to return
include: { ... }, // Optional: relations to include
});
select and include control the returned shape — see Selecting Fields.
Conditional Deletes
The where may narrow the unique lookup with non-unique scalar filters and
AND / OR / NOT:
// delete this token, but only if it has already expired
await client.token.delete({
where: { id: "tok_1", expiresAt: { lt: new Date() } },
});
If the unique key matches but the filter excludes the row, the delete is a
NotFoundError and the row survives. See
Narrowing a Unique Lookup
for the full where shape.
Cascading Deletes
When a record is deleted, related records are handled based on onDelete:
const post = s.model({
authorId: s.string(),
author: s
.toOne(() => user)
.fields("authorId")
.references("id")
.onDelete("cascade"), // Delete posts when user is deleted
});
| Action | Behavior |
|---|---|
cascade |
Delete related records |
setNull |
Set FK to null |
restrict |
Prevent deletion |
noAction |
Database default |
Soft Delete Pattern
To keep deleted rows and hide them from queries, use the official
soft-delete extension: delete then writes a
deletedAt time instead of removing the row, and every read, count and
relation skips it.
import { softDelete } from "viborm/soft-delete";
const post = s.model({
id: s.string().id(),
title: s.string(),
deletedAt: s.dateTime().nullable(),
});
const db = softDelete({ models: { post: { deletedAt: "deletedAt" } } })(client);
await db.post.delete({ where: { id } }); // sets deletedAt
await db.post.findMany(); // live posts only
await db.post.restore({ where: { id } }); // clears deletedAt
Examples
Delete User Account
async function deleteAccount(userId: string) {
// Delete in correct order due to FK constraints
await client.post.deleteMany({
where: { authorId: userId },
});
await client.profile.delete({
where: { userId },
}).catch(() => {}); // Ignore if no profile
return client.user.delete({
where: { id: userId },
});
}