How to find or create a record with Prisma?

Viewed 2067

Is this the best way to find or create a user in Prisma?

prisma.user.upsert({
  where: {
    id: user.id,
  },
  update: {
    id: user.id,
  },
  create: {
    id: user.id,
  },
})
1 Answers

Yes, you can use upsert to create a record. If the update property is empty, the record will not be updated.

Example:

const upsertUser = await prisma.user.upsert({
  where: {
    email: 'test@prisma.io',
  },
  update: {},
  create: {
    email: 'test@prisma.io',
    name: 'Test User',
  },
})

We plan to document this better: how upsert can behave as a findOrCreate. The link to the GitHub issue can be found here

For more information regarding upsert, you can read more in the Prisma Client API Reference section.

Related