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)
}