
{{ $('Map tags to IDs').item.json.title }}
How to Use Prisma ORM with Node.js
Prisma is a modern ORM (Object-Relational Mapping) tool that simplifies database interactions for Node.js applications. It provides type-safe queries, migrations, and a powerful schema management system. This tutorial will guide you through the process of setting up and using Prisma ORM in a Node.js project.
Prerequisites
- Node.js installed on your machine.
- A basic understanding of JavaScript and SQL databases.
- A PostgreSQL, MySQL, or SQLite database to connect to.
1. Setting Up Your Project
Create a new directory for your project and navigate into it:
mkdir my-prisma-app
cd my-prisma-app
npm init -y
2. Installing Prisma
Install Prisma and its CLI:
npm install prisma --save-dev
npx prisma init
The prisma init
command sets up the necessary files, including a schema.prisma
file for configuring your models and database connection.
3. Configuring the Database Connection
Open the schema.prisma
file created in the previous step and configure your database connection. For example:
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
Set your environment variables in the .env
file:
DATABASE_URL="postgresql://username:password@localhost:5432/mydatabase"
Make sure to replace username
, password
, and mydatabase
with your actual database credentials.
4. Defining Your Data Models
In the same schema.prisma
file, you can define your models. For example:
model User {
id Int @id @default(autoincrement())
name String
email String @unique
}
model Post {
id Int @id @default(autoincrement())
title String
content String?
author User? @relation(fields: [authorId], references: [id])
authorId Int?
}
These models define a User and a Post with a one-to-many relationship.
5. Running Migrations
To create the database tables based on your models, run:
npx prisma migrate dev --name init
This command applies migrations and updates the database schema.
6. Using Prisma Client
After setting up the models, you can use the Prisma Client to interact with the database:
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();
async function main() {
const newUser = await prisma.user.create({
data: {
name: 'Alice',
email: '[email protected]'
}
});
console.log(newUser);
}
main();
7. Handling Errors and Closing Connections
Wrap your database operations in try-catch blocks to handle errors gracefully. After your operations, ensure to disconnect:
async function main() {
try {
// your code here
} catch (error) {
console.error(error);
} finally {
await prisma.$disconnect();
}
}
8. Conclusion
By following this tutorial, you have successfully set up Prisma ORM in your Node.js project and learned how to interact with your database efficiently. Prisma provides a robust, type-safe API that simplifies working with database operations. Explore more advanced features and querying options to enhance your application further!