December 20, 20242 min read
Database Patterns with Prisma ORM
Learn effective database patterns and best practices using Prisma ORM for scalable applications.
Prisma has become the go-to ORM for TypeScript applications. Let's explore patterns that will make your database layer rock solid.
Setting Up Prisma
Initialize Prisma in your project:
npx prisma init
Define your schema:
model User {
id String @id @default(cuid())
email String @unique
name String?
posts Post[]
createdAt DateTime @default(now())
}
model Post {
id String @id @default(cuid())
title String
content String?
author User @relation(fields: [authorId], references: [id])
authorId String
}
Efficient Queries
Use select to fetch only needed fields:
const users = await prisma.user.findMany({
select: {
id: true,
name: true,
email: true,
},
});
Transactions
Handle complex operations atomically:
const result = await prisma.$transaction(async (tx) => {
const user = await tx.user.create({
data: { email, name },
});
await tx.post.create({
data: { title: "Welcome!", authorId: user.id },
});
return user;
});
Soft Deletes
Implement soft deletes with a middleware:
prisma.$use(async (params, next) => {
if (params.action === "delete") {
params.action = "update";
params.args.data = { deletedAt: new Date() };
}
return next(params);
});
Performance Tips
- Use connection pooling in production
- Index frequently queried fields
- Batch operations when possible
- Use
findFirstinstead offindManywhen expecting one result