Seeding Relational Data with Prisma

Jordan McRae's profile picture

Jordan McRae

Full Stack JavaScript Developer

ยท 4 min read


Overview

Prisma is a super simple ORM for your SQL databases. Let's run through how we seed relational data with it. You can also check out the sample app on Github.

Our Schema

Let's assume your Prisma.schema file looks like this:

datasource db { provider = "postgresql" url = env("DATABASE_URL") } generator client { provider = "prisma-client-js" } model User { id String @id @default(uuid()) createdAt DateTime @default(now()) updatedAt DateTime @updatedAt posts Post[] } model Post { id String @id @default(uuid()) createdAt DateTime @default(now()) updatedAt DateTime @updatedAt text String user User @relation(fields: [userId], references: [id]) userId String }

Here we have a User model that can have many Posts, and a Post belongs to a User.

Seeding Our Dev Database

Assuming you've got Prisma set up already (if you don't, check out the docs), let's create some dummy data for our development environment.

  1. Inside of your project's prisma folder, create a new folder called seed. This is where we will set up our seeding program, as well as our dummy data.
  2. Inside of your seed folder, create a new file called index.js, and a new folder called data.
  3. Inside of your data folder, create two files: users.js and posts.js.

Your folder structure should look something like this:

Prisma seed folder structure

Inside of your users.js file, let's create two dummy users that match our schema:

module.exports = [ // User 1 { id: 'f1bdf45e-1b1c-11ec-9621-0242ac130002', createdAt: new Date( 'Tue Sep 21 2021 16:16:50 GMT-0400 (Eastern Daylight Time)' ), updatedAt: new Date( 'Tue Sep 21 2021 16:16:50 GMT-0400 (Eastern Daylight Time)' ), }, // User 2 { id: '9371f314-1c93-11ec-9621-0242ac130002', createdAt: new Date( 'Tue Sep 21 2021 16:16:50 GMT-0400 (Eastern Daylight Time)' ), updatedAt: new Date( 'Tue Sep 21 2021 16:16:50 GMT-0400 (Eastern Daylight Time)' ), } ];

Inside of your posts.js file, let's create a post for each user.

Note: in the userId field for each post, you'll need to use a user's id from the users.js file we created in order to link up the relationship:

module.exports = [ // User 1's Post { id: '8e3399e6-1d94-11ec-9621-0242ac130002', createdAt: new Date( 'Tue Sep 21 2021 16:16:50 GMT-0400 (Eastern Daylight Time)' ), updatedAt: new Date( 'Tue Sep 21 2021 16:16:50 GMT-0400 (Eastern Daylight Time)' ), text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent sed.', userId: 'f1bdf45e-1b1c-11ec-9621-0242ac130002', }, // User 2's Post { id: '9197dea8-1d94-11ec-9621-0242ac130002', createdAt: new Date( 'Tue Sep 21 2021 16:16:50 GMT-0400 (Eastern Daylight Time)' ), updatedAt: new Date( 'Tue Sep 21 2021 16:16:50 GMT-0400 (Eastern Daylight Time)' ), text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent sed.', userId: '9371f314-1c93-11ec-9621-0242ac130002', } ];

Inside of the prisma/seed/index.js file is where the magic happens. This is where we'll write our code to tell Prisma what to do with the dummy data we just wrote. Inside of your index.js file, let's use the following code:

const { PrismaClient } = require('@prisma/client'); const prisma = new PrismaClient(); const Users = require('./data/users'); const Posts = require('./data/Posts'); async function runSeeders() { // Users await Promise.all( Users.map(async (user) => prisma.user.upsert({ where : { id: user.id }, update: {}, create: user, }) ) ); // Posts await Promise.all( Posts.map(async (post) => prisma.post.upsert({ where: { id: post.id }, update: {}, create: post, }) ) ); } runSeeders() .catch((e) => { console.error(`There was an error while seeding: ${e}`); process.exit(1); }) .finally(async () => { console.log('Successfully seeded database. Closing connection.'); await prisma.$disconnect(); });

And the last step is run our seed utility! Inside of your package.json file, create a new "script" entry:

{ "scripts": { "seed": "prisma db push && node prisma/seed/index.js" } }

What this command is doing is telling Prisma to sync up your database with the models you defined in your schema, and then running our seed utility.

You can now run this with either yarn seed or npm run seed!

Once it completes, you can check out your data using the command prisma studio.

And voila! You've successfully seeded some relational data. If you'd like to try it yourself, you can check out the sample app on Github.


Prisma
JavaScript
PostgreSQL
SQL
Share

Stack Five is a React and NodeJS consulting company that strives to push the boundaries of the web and build meaningful things. If you're looking to create a cutting-edge web application or need software engineering resources for your project, please contact us.

Stack Five logo

2021 Stack Five Inc. | Toronto, Canada