How to Create a Seed File in Prisma

Creating a seed file in Prisma is like laying a solid foundation.

In this article, I'll show you how to create a seed file and run it to populate your database.

I'll assume you have already got Prisma setup and installed so we can jump straight into the seed file setup:

Create your seed file

In your /prisma directory, create a new file called seed.js (or .ts if that's your flavor).

Then you need to point to this in your schema.prisma. Update your generator to know where your seed data is:

generator client {
  provider = "prisma-client-js"
  seed    = "prisma/seed.js" // or seed.ts if you're using TypeScript
}

Adding data

I'm going to assume we have a simple schema with the following structure:

model User {
  id    Int     @id @default(autoincrement())
  name  String
  email String  @unique
}

Now to populate our data, I'm also going to use a library called Chance.js here's a link to the docs.

Run npm install chance to get it into your project.

This will let us generate data rather than manually write it.

Here's the script I create inside seed.js:

const { PrismaClient } = require('@prisma/client');
const Chance = require('chance');

// By passing a number, we get a repeatable source of `random` generation. So I guess I mean, not random data. 🤣
const chance = new Chance(1);
const prisma = new PrismaClient();

// A function to make an array of data where `count` is the number of records
const generateUsers = (count) => {
  return Array(count)
    .fill(null)
    .map(() => ({
      name: chance.name(),
      email: chance.email(),
    }));
};

// Create 50 users
const userData = generateUsers(50);


async function main() {
  console.log(`Start seeding, please wait...`);
  // Iterate over each one to ensure they always save in the same order
  userData.forEach(async (user) => {
    await prisma.user.upsert({
      where: { email: user.email },
      update: {},
      create: user,
    });
     console.log(`Added user: ${user.name} - ${user.email}`);
  });
  console.log(`Seeding finished.`);
}

main()
  .catch((e) => {
    console.error(e);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
  });

Run the seed file

Now you can seed your database by running:

npx prisma db seed

And that's it!

You should now see the data in your database. You can use the npx prisma studio to open up your database and inspect the data.

Prisma
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.