Skip to content

Prisma, how to clear the database

New Course Coming Soon:

Get Really Good at Git

While testing a site that used Prisma I had the need to clear the database from time to time, to clear the test data I entered.

You can clear items entered by using:

await prisma.user.deleteMany({})

If for some reason you want to iterate on the items to do some processing, you can iterate over them in this way:

const users = await prisma.user.findMany({})

const deleteUser = async (user) => {
  return await prisma.user.delete({
    where: { id: user.id }
  })
}

const deleteUsers = async () => {
  users.map((user) => deleteUser(user))
}

deleteUsers()

In this case I am not doing anything more than the previous example, which makes all this code redundant, but you could do anything you want inside deleteUser().

I had a problem though because I had a relation between 2 tables, tweets and users. A tweet was associated to a user. First I had to remove all tweets, then remove all users, so I wrote this function:

export const clearData = async (prisma) => {
  const users = await prisma.user.findMany({})
  const tweets = await prisma.tweet.findMany({})

  const deleteUser = async (user) => {
    return await prisma.user.delete({
      where: { id: user.id }
    })
  }
  const deleteTweet = async (tweet) => {
    return await prisma.tweet.delete({
      where: { id: tweet.id }
    })
  }

  const deleteTweets = async () => {
    return Promise.all(tweets.map((tweet) => deleteTweet(tweet)))
  }

  const deleteUsers = async () => {
    return Promise.all(users.map((user) => deleteUser(user)))
  }

  await deleteTweets()
  await deleteUsers()
}

Notice the use of Promise.all() to wrap users.map() so I could use await on it, so all tweets are removed before I start deleting users.

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching May 21, 2024. Join the waiting list!
→ Read my SQL Tutorial on The Valley of Code

Here is how can I help you: