Prisma ORM Database Guide
Master Prisma ORM for type-safe database access.
What Is Prisma?
Prisma is a modern ORM for Node.js and TypeScript. Type-safe queries, auto-completion, and migrations make database work enjoyable.
Setup
npm install prisma @prisma/client
npx prisma init
Schema Definition
// prisma/schema.prisma
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
posts Post[]
createdAt DateTime @default(now())
}
model Post {
id Int @id @default(autoincrement())
title String
content String?
published Boolean @default(false)
author User @relation(fields: [authorId], references: [id])
authorId Int
}
Migrations
npx prisma migrate dev --name init
npx prisma generate
CRUD Operations
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
// Create
const user = await prisma.user.create({
data: { email: 'a@b.c', name: 'John' }
});
// Read with relations
const users = await prisma.user.findMany({
include: { posts: true }
});
// Update
await prisma.user.update({
where: { id: 1 },
data: { name: 'Jane' }
});
Conclusion
Prisma makes database work enjoyable and type-safe. Migrations and auto-generated types prevent many errors.