Blog

My Journey as a Web Developer

Why Use Prisma?

12/04/2023

author avatar

What is Prisma?

Prisma is an open-source database toolkit that simplifies database access and management for modern applications. It provides an Object-Relational Mapping (ORM) layer that allows developers to interact with databases using a strongly-typed and intuitive API. It simplifies working with databases.

Why Prisma though?

For the longest time, I relied on Mongoose as my go-to ORM when working with MongoDB. It served its purpose, allowing me to interact with the database in a structured manner. However, everything changed when I discovered Prisma. From the moment I started using Prisma, I realized how much more intuitive and streamlined the experience of working with databases could be. Prisma's open-source toolkit provided a refreshing approach to database access and management. With its powerful Object-Relational Mapping (ORM) layer and declarative Prisma Schema, I found myself immersed in a world where database operations became effortlessly intuitive.

Gone were the days of cumbersome query construction and manual type casting. Prisma abstracted away the complexities, generating MongoDB queries seamlessly behind the scenes. The strong typing and validation offered by Prisma ensured that my queries aligned perfectly with the defined schema, preventing runtime errors and boosting productivity.

Transitioning from Mongoose to Prisma was a paradigm shift, empowering me to focus on my application logic rather than getting caught up in the intricacies of database management.

Benefits of Prisma

Strongly Typed Schema

Prisma allows you to define a strongly typed schema for your database. This means that you can catch errors at compile-time instead of runtime, making it easier to catch bugs before they become a problem. With Mongoose, you're limited to runtime type checks, which can result in hard-to-debug issues.

Database-Agnostic

Prisma is database-agnostic, meaning that it can work with any database that supports SQL or a similar query language. With Mongoose, you're limited to MongoDB, which can be a problem if you need to switch to a different database down the line.

Automatic Query Generation

Prisma generates SQL queries automatically based on your schema definition. This saves time and reduces the likelihood of errors. With Mongoose, you need to write queries manually, which can be time-consuming and error-prone.

Type-Safe Querying

Prisma offers type-safe querying, meaning that you can't make queries that violate the schema definition. This helps to prevent runtime errors caused by incorrect queries. With Mongoose, there's no type safety, which can lead to hard-to-debug issues.

Powerful Tooling

Prisma comes with powerful tooling, including a database migration system, a query editor, and a schema visualizer. These tools make it easier to work with your database and understand its structure. With Mongoose, you need to rely on third-party tools or write your own.

Setting up Prisma

Add the Prisma CLI as a dev dependency. We will also need the Prisma client, so we will add that here too.

npm install prisma --save--dev @prisma/client

Now invoke the Prisma CLI

npx prisma

Now to set up your Prisma project run

npx prisma init

This will create a folder and file prisma/schema.prisma. It also creates a .env file if there isn't one there and it adds a DATEBASE_URL variable.

Connecting to the Database

For this tutorial, we will be using MongoDB.

Inside the newly create schema.prisma file we add the datasource.

generator client {
  provider = "prisma-client-js"
}
datasource db {
  provider = "mongodb"
  url      = env("DATABASE_URL")
}

We grab our MongoDB url and place it in the .env file. Make sure to place the username and password in the correct positions. Generally the format is as below. mongodb+srv://username:password@connectionstring.

Prisma Client

We already installed the prisma client package above. Before we go ahead and create the schema, we need to handle that client and make sure only one is running at a time.

import { PrismaClient } from "@prisma/client"

let prisma
if (process.env.NODE_ENV === "production") {
  prisma = new PrismaClient()
} else {
  if (!global.cachedPrisma) {
    global.cachedPrisma = new PrismaClient()
  }
  prisma = global.cachedPrisma
}

export const db = prisma

Creating a Schema in Prisma

Here's an example of how to create a schema in Prisma:

// Define the schema
model User {
  id       Int      @id @default(autoincrement())
  email    String   @unique
  name     String?
  password String
}

To push those schema changes, we run the following.

npx prisma db push

In this example, we're defining a User model with an ID, email, name, and password field. The @id attribute indicates that the ID field is the primary key, and the @unique attribute indicates that the email field is unique.

Comparison to Mongoose

Now let's compare this to how we would define the same schema in Mongoose:

const userSchema = new mongoose.Schema({
  email: { type: String, unique: true },
  name: String,
  password: String,
});

In Mongoose, we define a schema using a JavaScript object. While this is relatively straightforward, it's not strongly typed and can lead to runtime errors if the schema is not defined correctly.

Prisma Studio

Perhaps one of the greatest features that comes with using Prisma is the use of Prisma studio.

npx prisma studio

It's a really handle data exploration tool that allows us to see our data within a simple tabular interface. It shows the relationships at a glance, which you cannot do in something like Mongo Compass.

You can also easily interact with the database, performing crud operations. It's essentially a spreadsheet for your database.

Conclusion

In conclusion, Prisma is a powerful and modern way to interact with databases. With its strongly typed schema, database-agnostic approach, automatic query generation, type-safe querying, and powerful tooling, Prisma makes it easier and more efficient to work with databases than ever before. Whether you're new to databases or an experienced developer, Prisma is a tool that you should definitely consider using in your next project.

← Blog Home