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