skip to Main Content

I have a schema as follows:

model Player {
  id        String    @id @default(auto()) @map("_id") @db.ObjectId
  steam_id  String    @unique
  name      String
  level     Int       @default(1)
  elo       Float     @default(1500)
  games     Game[]    @relation(fields: [game_ids], references: [id])
  game_ids  String[]  @db.ObjectId

  clients   Client[]

  user      User?     @relation(fields: [user_id], references: [id])
  user_id   String?    @db.ObjectId @unique

  created_at        DateTime    @default(now())
  updated_at        DateTime    @updatedAt
  @@map("players")
}

As you can see, user_id is an optional field. However the relation REQUIRES it to be marked as unique. In doing so, I get the following error: duplicate key { user_id: null }

What can I do here?

2

Answers


  1. Chosen as BEST ANSWER

    It's honestly a bug by the Prisma team.

    To fix it all you have to do is go into your collection indexes and mark the index as "sparse".

    You can do it programmatically too.


  2. This is a scenario that’s currently not supported by Prisma.

    There’s a long running discussion/feature request that you can check here. Quoting from that issue:

    [..] I think the reason we don’t support this yet is because Postgres is the only database we support that behaves this way, the others reject duplicate NULLs.

    How I would work around this is remove the unique constraint and do the check in code: if user_id is non-null, query DB to see if the value already exists. If yes, reject the insert.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search