Prisma.js Cheatsheet



This Prisma.js cheatsheet provides a concise reference to key Prisma concepts, it is a Javascript library, including schema modeling, database migrations, and CRUD operations. It covers topics such as relations, filtering, pagination, middleware, and advanced querying with practical code examples. Designed to help developers build type-safe, scalable, and efficient database applications, this guide serves as a quick resource for leveraging the full power of Prisma in modern web development.

Table of Contents

  1. Introduction
  2. Installation
  3. Initialize Prisma
  4. Setup a Database
  5. Database Schema
  6. Initialize Your Database
  7. Install Prisma Client
  8. Using Prisma Client
  9. Schema Models
  10. CRUD Operations
  11. Filters
  12. Migrations
  13. Relations
  14. Pagination
  15. Advanced Querying
  16. Middleware
  17. Prisma Studio

Introduction

Prisma is a tool of type ORM (Object Relational Mapping) that is used in Node.js and TypeScript. It reduces working with databases to fundamental operations, offering a type-safe query API, migrations, and support for relational databases. I believe that Prisma is perfect for the modern, high-tempo back-end application.

Installation

Install Prisma CLI and Prisma Client using npm. Required for schema migrations and database interactions.

npm init -y

Install Prisma and dependencies:

npm i -D prisma @prisma/client

For TypeScript projects:

npm i -D typescript ts-node @types/node nodemon

Example:

{
"compilerOptions": {
"sourceMap": true,
"outDir": "dist",
"strict": true,
"lib": ["esnext"],
"esModuleInterop": true
}
}

Initialize Prisma

Run npx prisma init to create a prisma directory and .env file. This initializes the Prisma setup.

npx prisma init --datasource-provider postgresql

Setup a Database

Configure your database connection in the .env file. Use Prisma db pull to introspect an existing database.

Add database connection URI to .env:

DATABASE_URL="postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=SCHEMA"

If you already have data, pull the schema:

npx prisma db pull

Database Schema

Define database tables using the Prisma schema file (schema.prisma). Models represent tables in a structured format.

Example schema:

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

model Post {
    id String @id @default(uuid())
    title String
    content String?
    published Boolean @default(false)
    createdAt DateTime @default(now())
    updatedAt DateTime @updatedAt
    author User @relation(fields: [authorId], references: [id])
    authorId String
}

Initialize Your Database

Apply schema changes to your database with npx prisma migrate dev. This creates necessary tables and relations.

Apply schema changes to the database:

npx prisma migrate dev --name init

Install Prisma Client

Prisma Client is required to interact with the database.

npm i @prisma/client

Regenerate Prisma Client if needed:

npx prisma generate

Using Prisma Client

Import and initialize Prisma Client in your application. Use it to query, insert, update, and delete records.

Import and create a Prisma Client:

import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient({
    log: ['query', 'info', 'warn'],
});

Query example:

async function main() {
    const users = await prisma.user.findMany();
    console.log(users);
}
main().catch((e) => {
    throw e;
}).finally(async () => {
    await prisma.$disconnect();
});

Schema Models

Models define database tables with fields, data types, and constraints. Prisma supports enums and relations.

model User {
    id String @id @default(uuid())
    name String?
    email String @unique
    role Role @default(USER)
}

enum Role {
    USER
    ADMIN
}

CRUD Operations

Perform Create, Read, Update, and Delete operations using Prisma Client. These are essential for database manipulation.

CREATE: Use prisma.user.create() to insert a new user. Pass the required data in the data object.

const newUser = await prisma.user.create({
    data: {
        name: 'Pam',
        email: 'pam@paper.com',
        age: 26,
    },
});

UPDATE: Use prisma.user.findMany() to fetch users. Supports filters like where, select, and include.

const updatedUser = await prisma.user.update({
    where: { email: 'pam@paper.com' },
    data: { age: { increment: 1 } },
});

DELETE: Use prisma.user.update() to modify records. Supports incrementing values and updating specific fields.

const deletedUser = await prisma.user.delete({
    where: { email: 'pam@paper.com' },
});

READ: Use prisma.user.delete() to remove records. Requires a where condition to specify the target record.

const users = await prisma.user.findMany({
    where: { age: { gt: 25 } },
});

Filters

Use conditional queries to filter results based on fields. Filters include contains, AND, OR, and comparison operators.

Basic Filters: Use conditions like contains, gt, and lt in where clauses to filter data.

const filteredUsers = await prisma.user.findMany({
    where: {
        name: { contains: 'a' },
        age: { gt: 30 },
    },
});

AND/OR: Combine multiple filters using AND and OR operators for complex queries.

const users = await prisma.user.findMany({
    where: {
        AND: [
            { age: { gt: 20 } },
            { email: { contains: 'paper' } },
        ],
    },
});

Array Filtering: Filter nested relations using some, none, or every. Useful for filtering related records.

const posts = await prisma.user.findMany({
    where: {
        posts: {
            some: { title: 'Hello World' },
               },
            },
});

Migrations

Migrations apply schema changes to your database. Use npx prisma migrate dev to track and update schema versions.

npx prisma migrate dev --name init
# Apply: npx prisma migrate deploy

Relations

Define relationships between models using @relation fields. Prisma supports one-to-one, one-to-many, and many-to-many relations.

model User {
    id Int @id @default(autoincrement())
    posts Post[]
}

model Post {
    id Int @id @default(autoincrement())
    author User @relation(fields: [authorId], references: [id])
    authorId Int
}

Pagination

Fetch paginated results using skip and take options. This is useful for handling large datasets efficiently.

const posts = await prisma.post.findMany({
    skip: 10,
    take: 10,
});

Advanced Querying

Sort, filter, and search data with Prisma queries. Use orderBy, groupBy, and advanced where conditions.

const posts = await prisma.post.findMany({
    where: { published: true },
    orderBy: { createdAt: 'desc' },
});

Middleware

Middleware functions modify requests before execution. Useful for logging, validation, and enforcing business rules.

prisma.$use(async (params, next) => {
    console.log(params);
    return next(params);
});

Prisma Studio

A GUI tool for managing database records visually. Start it using npx prisma studio.

npx prisma studio

Access Prisma Studio at http://localhost:5555.

Advertisements