intermediate 16 min read

Prisma ORM

Modern database access with Prisma: schema definition, migrations, and type-safe queries.

Prisma ORM

// schema.prisma\n// datasource db {\n//   provider = \"postgresql\"\n//   url      = env(\"DATABASE_URL\")\n// }\n//\n// model User {\n//   id        Int      @id @default(autoincrement())\n//   name      String\n//   email     String   @unique\n//   posts     Post[]\n//   createdAt DateTime @default(now())\n// }\n//\n// model Post {\n//   id        Int      @id @default(autoincrement())\n//   title     String\n//   content   String?\n//   published Boolean  @default(false)\n//   author    User     @relation(fields: [authorId], references: [id])\n//   authorId  Int\n// }\n\nimport { PrismaClient } from '@prisma/client';\nconst prisma = new PrismaClient();\n\n// Create\nconst user = await prisma.user.create({\n  data: { name: 'Alice', email: '[email protected]' },\n});\n\n// Read with relations\nconst usersWithPosts = await prisma.user.findMany({\n  where: { email: { contains: 'test' } },\n  include: { posts: { where: { published: true } } },\n  orderBy: { name: 'asc' },\n  take: 10,\n});\n\n// Update\nawait prisma.user.update({\n  where: { id: 1 },\n  data: { name: 'Bob' },\n});\n\n// Delete\nawait prisma.user.delete({ where: { id: 1 } });\n\n// Aggregations\nconst stats = await prisma.post.aggregate({\n  _count: true,\n  _avg: { views: true },\n});

Examples

const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

async function createUserWithPosts(name, email, postTitles) {
  // Use a transaction for atomicity
  const result = await prisma.$transaction(async (tx) => {
    const user = await tx.user.create({
      data: { name, email },
    });

    const posts = await Promise.all(
      postTitles.map(title =>
        tx.post.create({
          data: { title, authorId: user.id },
        })
      )
    );

    return { user, posts };
  });

  return result;
}

// Query with pagination and filtering
async function getPaginatedPosts(page = 1, pageSize = 10) {
  const skip = (page - 1) * pageSize;

  const [posts, total] = await Promise.all([
    prisma.post.findMany({
      skip,
      take: pageSize,
      orderBy: { createdAt: 'desc' },
      include: { author: { select: { name: true } } },
    }),
    prisma.post.count(),
  ]);

  return {
    data: posts,
    meta: { page, pageSize, total, totalPages: Math.ceil(total / pageSize) },
  };
}

console.log('Prisma client ready');

Your Notes

Sign in to take notes for this lesson.

Quiz

Databases & ORMs Quiz

0 questions

Sign in to take quiz

Discussion

Sign in to join the discussion.

Flashcards

Sign in to create flashcards.