i have some code that loops through a list of emai...
# orm-help
j
i have some code that loops through a list of emails and creates users from it if conditions are met. there can be several hundred users. it looks like this:
Copy code
responses.map(r => {

            if (emailSchema.isValidSync(creatorEmail))
              await db.user.upsert({
                where: {
                  email: r.creatorEmail,
                },
                update: {},
                create: {
                  email: r.creatorEmail,
                },
              })

            if (emailSchema.isValidSync(approverEmail))
              await db.user.upsert({
                where: {
                  email: r.approverEmail,
                },
                update: {},
                create: {
                  email: r.approverEmail,
                },
              })
      })
the user model has a unique constraint on the email column:
Copy code
model User {
  id            String    @id @default(cuid())
  email         String?   @unique
  // etc...
}
i intermittently get `Unique constraint failed on the fields: (
email
)` errors 😞 is this a race condition? if so, how can i fix it?
r
This is due to
map
running everything asynchronously and you have a condition with
upsert
I would suggest using interactive transactions in this case so that there are no conflicts.
j
yessss
aha, that's the one
ty
💯 1