11

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,
  },
})
grabury
  • 4,797
  • 14
  • 67
  • 125

1 Answers1

25

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.

Nurul Sundarani
  • 5,550
  • 3
  • 23
  • 52
  • How to handle if email exist in Prisma? When using Sequelize, we can handle like this following code. https://www.codegrepper.com/code-examples/javascript/sequelize+findorcreate – Rahmat Oktrifianto Jul 16 '22 at 16:03