Getting Started with Prisma ORM: Simplifying Database Management

Aaryan Shrivastava - Sep 9 - - Dev Community

Problem Statement

Before diving into Prisma ORM and understanding what an ORM is, let’s first tackle a common problem.
Imagine you’re building an app to track your workouts. You want to log things like which muscle groups you trained, the exercises you did, and how many reps you completed each day. To make this happen, you need a backend system that can:

  • Save all this data into a database.
  • Retrieve it whenever you need it.
  • Maybe later, even update or delete the data as your workouts evolve.

The question now is: Which database should we use?

You have two main options: NoSQL or SQL databases. Initially, we might lean toward MongoDB (a popular NoSQL database) because it’s familiar and easy to get started with. But after learning about the benefits of SQL databases—such as better data relationships, structured querying, and stronger consistency—you decided to switch to a SQL database instead
But here’s the challenge: you don’t know SQL. While you’ve built APIs with Express and MongoDB before, SQL is new territory. Does this mean you have to start from scratch and learn SQL just to make this work?

Enter the Magic of ORMs

What is an ORM?

ORM (Object-Relational Mapping) is like a translator between your code and the database.
Normally, to store or retrieve data from the database, you’d need to write complex queries that tell the database exactly what to do. ORM makes this process easier by allowing you to work with objects in your code, and it automatically handles the process of translating these objects into database-friendly terms.

So, with ORM, you can focus on writing code, while it takes care of talking to the database behind the scenes.

Why ORM?

Apart from abstracting the queries, ORMs also have the following benefits

  1. It has a very simple syntax that converts objects under into queries under the hood.
  2. Due to abstraction, ORMs enable us to switch databases while the underlying code remains the same.
  3. It supports type safety which also helps in auto completion (real lifesaver)
  4. Sometimes as the application grows, the schema for the database changes, and it becomes difficult to track all the commands that lead to the current schema. ORMs maintain all this for us in the form of migrations.

Prisma

For our case, we will be using Primsa ORM, as it is the most popular one, mostly for the following reasons:

  1. Schema Driven: Prisma uses a schema file where you define your database models. You describe the structure of your data fields, types, and relationships between models. Prisma uses this schema to generate the necessary code to interact with the database.

  2. Automatic Migrations: When you update your Prisma schema, it can automatically generate SQL migrations, which modify the actual database structure to match your new schema. This simplifies the process of keeping your database up-to-date as your application evolves.


Now let’s see how can we implement it in a fresh app.

Installing Prisma in the fresh app.

Initialize a Node.js Project


npm init -y
Enter fullscreen mode Exit fullscreen mode

Add Dependencies

npm install prisma typescript ts-node @types/node --save-dev
Enter fullscreen mode Exit fullscreen mode

Initialize typescript

npx tsc --init
Change `rootDit` to `src`
Change `outDir` to `dist`
Enter fullscreen mode Exit fullscreen mode

Initialize a Prisma project

npx prisma init
Enter fullscreen mode Exit fullscreen mode

Selecting your database

Prisma lets you choose between a few databases (MySQL, Postgres, Mongo)
You can update prisma/schema.prisma to set up what database you want to use.
We will be using Postgres for our case. Which is by default present in boilerplate code.

Image description


Tip 💡 - Install VScode Prisma Extension to better visualize Prisma

Image description

Defining your data model

Prisma expects you to define the shape of your data in the schema.prisma file
Below is the schema for our use case.

Image description

Notice how we have defined relationships to relate two models. Prisma enables us to define relationships to relate tables with each other.

Generate migrations

You have created a single schema file. You haven’t yet run the CREATE TABLE commands. To run those and create migration files, run

npx prisma migrate dev --name Initialize the schema
Enter fullscreen mode Exit fullscreen mode


Tip 💡 - Check the prisma/migrations folder every time you run this command and see how Prisma keeps track of schema changes.

Generating the prisma client

After you define your data models in the schema.prisma file, Prisma generates a client that includes all the necessary functions to create, read, update, and delete (CRUD) records in your database.
Run the following command after the schema is set up.

npx prisma generate
Enter fullscreen mode Exit fullscreen mode

Using PrismaClient

After running the generate command Prisma takes your schema and automatically generates a customized client tailored to your data models. This client contains functions to work with your database models directly.
Here’s what happens after the Prisma Client is generated, based on our workout schema:

Image description

Now just run the index.ts file to execute the code. And we should see the log.

Image description

You can also see this in the Postgres Dashboard, in our case, we have used neon.tech

Exercise Table

Image description

Workout Table

Image description

And there you have it! You've successfully set up your first backend application using Prisma.

.
Terabox Video Player