To start a Prisma project, follow these steps:
mkdir prisma-project && cd prisma-project
npm init -ynpm install @prisma/client
npm install -D prisma typescript ts-node @types/nodenpx prisma initThis command will create a prisma/ directory with:
schema.prisma– Your main Prisma schema file.env– Environment variables (e.g., database connection string)
Update the .env file with your database URL, for example, for PostgreSQL:
DATABASE_URL="postgresql://username:password@localhost:5432/mydb?schema=public"
Edit the schema.prisma file to define your data models:
// prisma/schema.prisma
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model User {
id Int @id @default(autoincrement())
name String
email String @unique
posts Post[]
}
model Post {
id Int @id @default(autoincrement())
title String
content String
authorId Int
author User @relation(fields: [authorId], references: [id])
}npx prisma migrate dev --name initThis will generate the migration files you see in the prisma/migrations/ folder.
npx prisma generateCreate index.ts to test your connection:
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
async function main() {
const user = await prisma.user.create({
data: {
name: "John Doe",
email: "john@example.com",
},
});
console.log(user);
}
main()
.catch((e) => console.error(e))
.finally(async () => {
await prisma.$disconnect();
});Make sure you have TypeScript configured (your tsconfig.json is already there). Then, run:
npx ts-node index.tsTo visually manage your database, you can use:
npx prisma studio