Seeding Databases using Prisma Seed Scripts
Database seeding is the process of populating your database tables with dummy or default records (for example, creating administrative login credentials or default product categories).
1. Registering the Seed Script
To set up a seeding script in TypeScript, add the prisma configuration block to your package.json file:
{
"name": "my-app",
"dependencies": {},
"prisma": {
"seed": "ts-node prisma/seed.ts"
}
}Make sure ts-node is installed in your development environment:
# Install ts-node development dependency
npm install -D ts-node2. Writing the Seeding Logic
Create a script file named seed.ts inside prisma/:
// prisma/seed.ts
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
async function main() {
console.log("Starting database seeding process...");
// 1. Clear existing database records
await prisma.post.deleteMany();
await prisma.user.deleteMany();
// 2. Create default admin user and associated post
const admin = await prisma.user.create({
data: {
email: "admin@company.com",
name: "System Administrator",
posts: {
create: [
{ title: "System Welcome Message" },
{ title: "Developer Integration Guide" },
],
},
},
});
console.log("Seeded user:", admin.email);
console.log("Database seeding completed successfully.");
}
main()
.then(async () => {
await prisma.$disconnect();
})
.catch(async (e) => {
console.error(e);
await prisma.$disconnect();
process.exit(1);
});3. Running the Seed Script
Execute the seed script using the Prisma CLI:
# Run database seed
npx prisma db seedThis command runs the registered script, populating your database with the defined test records. The seed command is also executed automatically during npx prisma migrate reset workflows.
Published on Last updated: