Youssef Samir

Get in touch

Prisma

Understand Prisma, a next-generation ORM that simplifies database access for Node.js and TypeScript applications.

1. Setup

Install Prisma

npm install prisma --save-dev
npx prisma init

Install Database Connector (PostgreSQL)

npm install @prisma/client

2. Prisma Schema (prisma/schema.prisma)

Data Source (PostgreSQL)

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

Generator

generator client {
  provider = "prisma-client-js"
}

Model Example

model User {
  id        Int      @id @default(autoincrement())
  email     String   @unique
  name      String?
  createdAt DateTime @default(now())
  posts     Post[]
}

model Post {
  id        Int      @id @default(autoincrement())
  title     String
  content   String?
  author    User     @relation(fields: [authorId], references: [id])
  authorId  Int
  createdAt DateTime @default(now())
}

3. Migrations

Generate Migration

npx prisma migrate dev --name init

Deploy Migration to Production

npx prisma migrate deploy

Reset Database

npx prisma migrate reset

4. Prisma Client

Import Prisma Client

import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()

Basic Queries

Find One

const user = await prisma.user.findUnique({
  where: { id: 1 },
})

Find Many

const users = await prisma.user.findMany()

Create

const newUser = await prisma.user.create({
  data: {
    email: 'user@example.com',
    name: 'John Doe',
  },
})

Update

const updatedUser = await prisma.user.update({
  where: { id: 1 },
  data: { name: 'Jane Doe' },
})

Delete

const deletedUser = await prisma.user.delete({
  where: { id: 1 },
})

Relations

const postWithAuthor = await prisma.post.findMany({
  include: { author: true },
})

Nested Create

const newPost = await prisma.post.create({
  data: {
    title: 'My First Post',
    content: 'Hello World',
    author: {
      connect: { id: 1 }
    }
  }
})

Nested Update

const updatedPost = await prisma.post.update({
  where: { id: 1 },
  data: {
    content: 'Updated Content',
    author: {
      update: { name: 'New Author' }
    }
  }
})

5. Prisma Client Commands

Generate Client

npx prisma generate

Studio (GUI for DB)

npx prisma studio

6. Prisma Query Filters

Filtering

Where

const users = await prisma.user.findMany({
  where: { email: 'user@example.com' }
})

OR Condition

const users = await prisma.user.findMany({
  where: {
    OR: [{ name: 'John' }, { email: 'john@example.com' }]
  }
})

AND Condition

const users = await prisma.user.findMany({
  where: {
    AND: [{ name: 'John' }, { email: 'john@example.com' }]
  }
})

Sorting

const users = await prisma.user.findMany({
  orderBy: { createdAt: 'desc' }
})

Pagination

const users = await prisma.user.findMany({
  skip: 10,
  take: 5
})

This cheatsheet should give you a solid reference for using Prisma in your project. If you need more advanced operations or specific examples, feel free to ask!