Working with Update Operations
1. Updating Single Record
await prisma.user.update({
where: { id: 1 },
data: { name: "Alice" }
});
| Aspect | Detail |
| Where | Must target unique field |
| Error | P2025 if not found |
2. Updating Multiple Records
const res = await prisma.post.updateMany({
where: { authorId: 1, published: false },
data: { published: true }
});
console.log(res.count);
| Aspect | Detail |
| Returns | Count of modified rows |
| No relations | Cannot nest writes |
3. Upserting Records
await prisma.user.upsert({
where: { email: "a@b.io" },
create: { email: "a@b.io", name: "Alice" },
update: { name: "Alice" }
});
| Block | Use |
where | Unique match |
create | Inputs when not found |
update | Inputs when found |
4. Using Where Clause Filters
| Update Variant | Where Type |
update | Unique only |
updateMany | Any filter |
5. Updating Nested Relations
await prisma.user.update({
where: { id: 1 },
data: {
posts: {
update: { where: { id: 5 }, data: { published: true } },
create: { title: "New" },
delete: { id: 8 }
}
}
});
| Op | Effect |
update / updateMany | Modify children |
upsert | Conditional create |
delete / deleteMany | Remove |
6. Incrementing Numeric Fields
await prisma.post.update({
where: { id: 1 },
data: { views: { increment: 1 } }
});
| Operator | SQL |
increment | views = views + n |
| Atomic | Safe under concurrent writes |
7. Decrementing Numeric Fields
| Operator | SQL |
decrement | field = field - n |
8. Multiplying Numeric Fields
| Operator | SQL |
multiply | field = field * n |
9. Dividing Numeric Fields
| Operator | SQL |
divide | field = field / n |
10. Setting Fields to Null
await prisma.user.update({ where: { id: 1 }, data: { deletedAt: null } });
| Constraint | Detail |
| Optional only | Required fields reject null |
| JSON | Use Prisma.JsonNull |