Prisma provides type-safe database access with an intuitive API and powerful migrations.
Setup
npm install prisma @prisma/client
npx prisma init
Schema Definition
// prisma/schema.prisma
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
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
}
Basic Queries
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
// Create
const user = await prisma.user.create({
data: {
email: 'alice@example.com',
name: 'Alice',
},
});
// Read
const users = await prisma.user.findMany();
const user = await prisma.user.findUnique({
where: { email: 'alice@example.com' },
});
// Update
const updated = await prisma.user.update({
where: { id: 1 },
data: { name: 'Alice Updated' },
});
// Delete
await prisma.user.delete({ where: { id: 1 } });
Relations
// Create with relation
const userWithPosts = await prisma.user.create({
data: {
email: 'bob@example.com',
posts: {
create: [{ title: 'First Post' }, { title: 'Second Post' }],
},
},
include: { posts: true },
});
// Query with relations
const usersWithPosts = await prisma.user.findMany({
include: { posts: true },
});
Migrations
# Create migration
npx prisma migrate dev --name init
# Apply migrations in production
npx prisma migrate deploy
Best Practices
- Use transactions for multiple operations
- Select only needed fields to optimize queries
- Use Prisma Studio for database exploration
- Handle connection pooling in serverless
Posted onnodejswith tags: