Question about handling upsert case

What is the best way to handle this case for upserts?

in prisma, my upsert code looks like this:
    await prisma.posts.upsert({
      create: {
        title: post.title,
        userId: req.user.id
      },
      update: { title },
      where: { id: post.id || '' }
    });

If the post was being created, post.id would be undefined, thus the || '' would make it such that no post was found with id of '', so it would create a new post

if the post was being updated, post.id would exist and it would find the post with the matching id and update it.

in drizzle, the upsert code i have now looks like this:
    await db
      .insert(posts)
      .values({
        id: post.id || crypto.randomUUID(),
        title: post.title,
        userId: req.user.id
      })
      .onConflictDoUpdate({ set: { title: post.title }, target: posts.id });

is there a better way to do this without needing to randomly generate the UUID for the
id
field? in the prisma code it was able to find no match on the id field, and just use the auto generate rule for the id field rather than me having to manually set it
Was this page helpful?