DEV Community

Cover image for How to perform non updating upserts in Prisma
Chris Bongers
Chris Bongers

Posted on • Originally published at daily-dev-tips.com

How to perform non updating upserts in Prisma

In our example yesterday, we are pushing specific playlists to our database. However, if we add a playlist twice, we will see that the URI is not unique and exists already.

There are several ways to go about this.
And for this example, I want to look at doing a non-updating upsert.

This means we check if the URI already exists. If this is the case, we perform an update.
If it doesn't exist, we perform the creation.

The small caveat here is that we push an empty update object.

This will result in the API returning the old existing object without updating it.

Upsert in Prisma

To perform an upsert in Prisma, you can use the upsert command.
It takes a where a query that should query on a unique field.

Then it comes with both the update and create functions like so:

const playlist = await prisma.playlist.upsert({
  where: {
    uri: uri,
  },
  update: {},
  create: playlistItem,
});
Enter fullscreen mode Exit fullscreen mode

And there you go. This gives us a super good way only to create this if it doesn't exist functionality.

You can find the complete example based on the Spotify database on GitHub.

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Top comments (0)