mongodbormschemaprisma

Prisma @unique null fails validation


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?


Solution

  • 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.