DEV Community

Cover image for Prisma CRUD Operations Guide
Md Enayetur Rahman
Md Enayetur Rahman

Posted on

Prisma CRUD Operations Guide

This guide will walk you through using Prisma for common database operations like creating, updating, upserting, and deleting records. We’ll also cover how to fetch only selected fields when querying.

  1. Creating Records

First, create a file called create.ts in the src directory for inserting multiple records using Prisma’s createMany method.

create.ts

import { PrismaClient } from '@prisma/client';

// Initialize Prisma Client
const prisma = new PrismaClient();

const main = async () => {
  const createMany = await prisma.post.createMany({
    data: [
      {
        title: 'title1',
        content: 'content1',
        authorName: 'authorName1',
      },
      {
        title: 'title2',
        content: 'content2',
        authorName: 'authorName2',
      },
      { 
        title: 'title3',
        content: 'content3',
        authorName: 'authorName3',
      }
    ]
  });

  console.log(createMany); // Outputs the count of records created
};

main();

Enter fullscreen mode Exit fullscreen mode

Running this file will create three records in the Post table, but only the count of records created will be returned.

  1. Updating Records Create a file named update.ts for updating records.

update.ts

import { PrismaClient } from '@prisma/client';

// Initialize Prisma Client
const prisma = new PrismaClient();

const main = async () => {
  // Update a single record
  const singleUpdate = await prisma.post.update({
    where: {
      id: 4,
    },
    data: {
      title: 'updated title',
      content: 'updated content',
      authorName: 'updated authorName',
    }
  });

  console.log(singleUpdate); // Returns the updated record
};

main();

Enter fullscreen mode Exit fullscreen mode

In this example, Prisma updates the post with id 4 and returns the updated record. The updatedAt field will be automatically updated by Prisma.

To update multiple records based on a condition, use updateMany:

import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

const main = async () => {
  const updateMany = await prisma.post.updateMany({
    where: {
      title: 'title2',
    },
    data: {
      published: true,
    }
  });

  console.log(updateMany); // Outputs the count of records updated
};

main();

Enter fullscreen mode Exit fullscreen mode

The updateMany method updates multiple records and returns the count of records modified.

  1. Upserting Records
  2. Upsert allows you to update a record if it exists or create a new record if it doesn’t. Create a file named upsert.ts:

upsert.ts

import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

const main = async () => {
  const upsert = await prisma.post.upsert({
    where: {
      id: 4,
    },
    update: {
      title: 'updated title',
      content: 'updated content',
      authorName: 'updated authorName',
    },
    create: {
      title: 'title1',
      content: 'content1',
      authorName: 'authorName1',
    }
  });

  console.log(upsert); // Returns the created or updated record
};

main();

Enter fullscreen mode Exit fullscreen mode

The upsert method will update the post with id 4 if it exists or create a new post if it doesn’t.

  1. Deleting Records

Create a file named delete.ts for deleting records.

delete.ts

import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

const main = async () => {
  // Delete a single record
  const deleteSingleRecord = await prisma.post.delete({
    where: {
      id: 4,
    }
  });

  console.log(deleteSingleRecord); // Returns the deleted record
};

main();

Enter fullscreen mode Exit fullscreen mode

This deletes the post with id 4 and returns the deleted record. To delete multiple records based on a condition, use deleteMany:

import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

const main = async () => {
  const deleteMany = await prisma.post.deleteMany({
    where: {
      published: false,
    }
  });

  console.log(deleteMany); // Outputs the count of records deleted
};

main();
Enter fullscreen mode Exit fullscreen mode

The deleteMany method deletes multiple records and returns the count of records removed.

  1. Selecting Specific Fields

Sometimes, you may not want to fetch all fields of a record. Use the select property to retrieve only the fields you need.

select example
Create a file named select.ts:

import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

const main = async () => {
  const findUnique = await prisma.post.findUnique({
    where: {
      id: 4,
    },
    select: {
      title: true,
      content: true,
    }
  });

  console.log(findUnique); // Returns only the title and content fields
};

main();

Enter fullscreen mode Exit fullscreen mode

Using select, only title and content are returned, allowing you to fetch just the required fields for efficient data handling.

This guide provides a foundational understanding of CRUD operations in Prisma, along with how to use select to fetch specific fields. These examples showcase the flexibility and power Prisma offers for managing database records.

Top comments (0)