Skip to content

Instantly share code, notes, and snippets.

@modster
Created December 5, 2021 06:24
Show Gist options
  • Save modster/27cff189b6bc157699fb8f649d5ab840 to your computer and use it in GitHub Desktop.
Save modster/27cff189b6bc157699fb8f649d5ab840 to your computer and use it in GitHub Desktop.
Seed a Prisma DB with npx

Create a new file named seed.js. This can be placed anywhere within your projects folder structure. The below example places it in the /prisma folder.

In the seed.js file, import Prisma Client, initialize it and create some records.

const { PrismaClient } = require('@prisma/client')
const prisma = new PrismaClient()

async function main() {
  const alice = await prisma.user.upsert({
    where: { email: '[email protected]' },
    update: {},
    create: {
      email: '[email protected]',
      name: 'Alice',
      posts: {
        create: {
          title: 'Check out Prisma with Next.js',
          content: 'https://www.prisma.io/nextjs',
          published: true,
        },
      },
    },
  })

  const bob = await prisma.user.upsert({
    where: { email: '[email protected]' },
    update: {},
    create: {
      email: '[email protected]',
      name: 'Bob',
      posts: {
        create: [
          {
            title: 'Follow Prisma on Twitter',
            content: 'https://twitter.com/prisma',
            published: true,
          },
          {
            title: 'Follow Nexus on Twitter',
            content: 'https://twitter.com/nexusgql',
            published: true,
          },
        ],
      },
    },
  })
  console.log({ alice, bob })
}

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

Add the prisma.seed to your package.json file:

{
  "name": "my-project",
  "version": "1.0.0",
  "prisma": {
    "seed": "node prisma/seed.js"
  }
}

To seed the database, run the db seed CLI command:

npx prisma db seed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment