Database Seeding Setup
Populating your database with initial data using Prisma seeds.
Database seeding is the process of populating a database with initial data. This is useful for development (having test users/data), demonstrations, or setting up default configurations.
Prisma provides a built-in mechanism for seeding your database.
1. Create the Seed File (prisma/seed.ts)
Create a file named seed.ts inside your prisma directory. This file will contain the logic for creating your initial data.
- Replace the example
prisma.user.createManycall with your actual Prisma model operations. - Add logic to seed any other necessary models. - UseskipDuplicates: truewhere appropriate if running the seed script multiple times shouldn't cause errors.
2. Configure package.json
Add a seed script and the Prisma seed configuration to your package.json file:
- The
db:seedscript provides a convenient way to run the Prisma seeding command. - The
prisma.seedconfiguration tells Prisma how to execute your TypeScript seed file usingts-node. - The
--compiler-options {"module":"CommonJS"}flag is often necessary to ensurets-nodehandles modules correctly in this context.
3. Install ts-node
4. Run the Seed Script
Execute the seed script using npm (or yarn):
Prisma will now execute your prisma/seed.ts file, populating your database with the initial data you defined.
Ensure your database connection URL in .env is correctly configured before
running the seed command. Make sure you have run prisma migrate dev or
prisma migrate deploy at least once to ensure your database schema exists.