DEV Community

Cover image for Outline: Add Prisma ORM to a Node.js project using PostgreSQL DB
Jude Eigbiremonlen
Jude Eigbiremonlen

Posted on

Outline: Add Prisma ORM to a Node.js project using PostgreSQL DB

Quick outline to add Prisma ORM to any Node.js or Express project using a PostgreSQL DB. This outline will work if adding Prisma to an existing or new Node.js project.

  • Install required packages and dependencies

Navigate to your project directory or create the project directory and install these required dependencies using any package manager you like:

npm install prisma@prev @types/node @types/pg --save-dev
Enter fullscreen mode Exit fullscreen mode
npm install @prisma/client@7 @prisma/adapter-pg pg dotenv
Enter fullscreen mode Exit fullscreen mode

The prisma package is a CLI tool that enables us run commands on the terminal like prisma init, migrate, pull and studio.
@prisma/client is the client library querying the database, @prisma/adapter-pg,pg & @types/pg are the node_postgres driver adapter, driver and TypeScript type definitions that connect Prisma to client Postgres database.

  • Initialize Prisma
npx prisma init --datasource-provider postgresql --output ../generated/prisma
Enter fullscreen mode Exit fullscreen mode

This command creates a prisma folder with a schema.prisma file in it; the file contains your db connection setup in it.
And also a .env and prisma configuration file prisma7.config.ts are created in the root directory.

  • Connect your database
DATABASE_URL="postgresql://user:password@localhost:5432/mydb?schema=public" 
Enter fullscreen mode Exit fullscreen mode

Edit the connection to match your database details.

  • Next step

Either pull your existing database using this command:

npx prisma db pull
Enter fullscreen mode Exit fullscreen mode

Or
update the prisma/schema.prisma file

generator client {
  provider = "prisma-client"
  output   = "../generated/prisma"
}
datasource db {
  provider = "postgresql"
}
model User {  
  id    Int     @id @default(autoincrement())  
  name  String  
  email String  @unique  
} 

## your other tables 
Enter fullscreen mode Exit fullscreen mode

Migrate and push your new database schema:

npx prisma migrate dev --name init 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)