Simple CRUD Operations with Prisma ORM


Simple CRUD Operations with Prisma ORM

It is critically important to perform database operations quickly and securely in modern web projects. Prisma ORM is a prominent Object Relational Mapping (ORM) tool for TypeScript and Node.js applications. It is especially appreciated by developers for its security, auto-completion, and ease of use. In this article, under the title "Simple CRUD Operations with Prisma ORM", we will cover how to set up Prisma for a project and how to perform basic CRUD (Create, Read, Update, Delete) operations.

Project Setup with Prisma

To start, first create a new Node.js project and install Prisma:

npm init -y
npm install prisma --save-dev
npm install @prisma/client
npx prisma init

After these steps, a prisma/schema.prisma file will be created and you will be able to define your database. For example, below is a simple User model:

model User {
  id    Int     @id @default(autoincrement())
  name  String
  email String  @unique
}

CRUD Operations: Basic Usage

After establishing the database connection, apply your first migration with npx prisma migrate dev. Now, let's look at sample codes for Simple CRUD Operations with Prisma ORM.

Create User

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

async function createUser() {
  const user = await prisma.user.create({
    data: {
      name: 'Ali Veli',
      email: 'ali.veli@example.com',
    },
  });
  console.log(user);
}

createUser();

List Users (Read)

async function getUsers() {
  const users = await prisma.user.findMany();
  console.log(users);
}

getUsers();

Update User

async function updateUser(id) {
  const updated = await prisma.user.update({
    where: { id },
    data: { name: 'New Name' },
  });
  console.log(updated);
}

updateUser(1); // updates the user with id = 1

Delete User

async function deleteUser(id) {
  const deleted = await prisma.user.delete({
    where: { id },
  });
  console.log(deleted);
}

deleteUser(1); // deletes the user with id = 1

Conclusion

Performing Simple CRUD Operations with Prisma ORM is quite easy and practical. Thanks to type safety, automatic code completion, and strong documentation that Prisma provides, you can easily manage complex database operations in your Node.js projects with fewer errors. By choosing Prisma ORM, which is preferred by the majority of developers, you can also add speed and security to your projects.