PrismaClientKnownRequestError: P2025
An operation failed because it depends on one or more records that were required but not found.
Youβre trying to update, delete, or connect to a record that doesnβt exist in the database.
Fix 1: Check If Record Exists Before Updating
// β Update assumes record exists
await prisma.user.update({
where: { id: 999 }, // π₯ If ID 999 doesn't exist
data: { name: 'Alice' },
});
// β
Use upsert (update or create)
await prisma.user.upsert({
where: { id: 999 },
update: { name: 'Alice' },
create: { id: 999, name: 'Alice', email: 'alice@example.com' },
});
Fix 2: Check Before Deleting
// β Delete non-existent record
await prisma.user.delete({ where: { id: 999 } }); // π₯
// β
Use deleteMany (returns count, doesn't throw)
const { count } = await prisma.user.deleteMany({ where: { id: 999 } });
if (count === 0) console.log('Record not found');
Fix 3: Relation Not Found
// β Connecting to a related record that doesn't exist
await prisma.post.create({
data: {
title: 'Hello',
author: { connect: { id: 999 } }, // π₯ User 999 doesn't exist
},
});
// β
Verify the related record exists first
const user = await prisma.user.findUnique({ where: { id: 999 } });
if (!user) throw new Error('User not found');
Fix 4: Handle the Error Gracefully
import { PrismaClientKnownRequestError } from '@prisma/client/runtime/library';
try {
await prisma.user.update({ where: { id }, data });
} catch (e) {
if (e instanceof PrismaClientKnownRequestError && e.code === 'P2025') {
return res.status(404).json({ error: 'Record not found' });
}
throw e;
}
Fix 5: Cascade Delete Issues
// β Deleting parent with required children
// β
Add cascade delete in schema
model User {
posts Post[] @relation(onDelete: Cascade)
}
Related resources
Related: What is PostgreSQL