0
0
NextJSframework~5 mins

CRUD operations with Prisma in NextJS

Choose your learning style9 modes available
Introduction

CRUD operations let you create, read, update, and delete data in your app. Prisma helps you do this easily with your database.

When you want to save new user info in your app.
When you need to show a list of items from your database.
When you want to change details of something already saved.
When you want to remove data that is no longer needed.
When building any app that stores and manages data.
Syntax
NextJS
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

// Create
await prisma.modelName.create({ data: { /* fields */ } });

// Read
await prisma.modelName.findMany();
await prisma.modelName.findUnique({ where: { id: value } });

// Update
await prisma.modelName.update({ where: { id: value }, data: { /* fields */ } });

// Delete
await prisma.modelName.delete({ where: { id: value } });

Replace modelName with your actual Prisma model name (like user or post).

Use await because Prisma operations are asynchronous.

Examples
This creates a new user with name and email.
NextJS
await prisma.user.create({ data: { name: 'Alice', email: 'alice@example.com' } });
This fetches all users from the database.
NextJS
const users = await prisma.user.findMany();
This updates the user with id 1 to have a new name.
NextJS
await prisma.user.update({ where: { id: 1 }, data: { name: 'Alice Updated' } });
This deletes the user with id 1.
NextJS
await prisma.user.delete({ where: { id: 1 } });
Sample Program

This program shows all four CRUD operations with Prisma on a user model. It creates a user, reads all users, updates the created user, then deletes it. Finally, it prints the results at each step.

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

const prisma = new PrismaClient();

async function main() {
  // Create a new user
  const newUser = await prisma.user.create({
    data: { name: 'Bob', email: 'bob@example.com' }
  });

  // Read all users
  const allUsers = await prisma.user.findMany();

  // Update the new user's name
  const updatedUser = await prisma.user.update({
    where: { id: newUser.id },
    data: { name: 'Bobby' }
  });

  // Delete the user
  await prisma.user.delete({ where: { id: updatedUser.id } });

  // Return all users after deletion
  const usersAfterDelete = await prisma.user.findMany();

  console.log('Created User:', newUser);
  console.log('All Users:', allUsers);
  console.log('Updated User:', updatedUser);
  console.log('Users After Delete:', usersAfterDelete);
}

main()
  .catch(e => console.error(e))
  .finally(async () => {
    await prisma.$disconnect();
  });
OutputSuccess
Important Notes

Always disconnect Prisma client with prisma.$disconnect() to avoid open connections.

Use try/catch or .catch() to handle errors in async Prisma calls.

Make sure your Prisma schema is set up and migrated before running CRUD operations.

Summary

CRUD means Create, Read, Update, Delete data.

Prisma provides easy methods to do CRUD with your database.

Use async/await and proper error handling when working with Prisma.