P
Prisma9mo ago
Risatoga

How to Implement an Optional One-to-One Relationship in Prisma with MongoDB?

Context I'm using Prisma 5.10.2 with MongoDB and attempting to set up an optional one-to-one relationship between two models based on the official Prisma documentation. However, I've encountered a problem with MongoDB's support for nullable unique fields. Models Here are the models I'm using (the ones recommended in the docs actually)
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
profile Profile? @relation(fields: [profileId], references: [id])
profileId String? @unique @db.ObjectId // relation scalar field (used in the `@relation` attribute above)
}

model Profile {
id String @id @default(auto()) @map("_id") @db.ObjectId
user User?
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
profile Profile? @relation(fields: [profileId], references: [id])
profileId String? @unique @db.ObjectId // relation scalar field (used in the `@relation` attribute above)
}

model Profile {
id String @id @default(auto()) @map("_id") @db.ObjectId
user User?
}
` Issue MongoDB does not support "nullable uniques," which means that users without a profile (where the profile property is null) are not unique and cause write operations to fail. Possible Solutions I've Considered - Changing to a One-to-Many Relationship: Modify the User model to handle an array of profiles but only use the first item. This approach seems hacky as it deviates from the intended one-to-one relationship structure. - Making the Profile Required: This would ensure uniqueness but defeats the purpose of the relationship being optional. Question Is there a standard approach to implementing optional one-to-one relationships in Prisma with MongoDB that avoids these issues, or is adapting one of the hacky solutions the only way? I'm relatively new to this (been learning for about 8 months), so any guidance or alternative suggestions would be greatly appreciated. Thank you!
3 Replies
Risatoga
RisatogaOP9mo ago
Stack Overflow
Prisma Mongodb: Optional 1:1 relation not working
I am trying to achieve a 1:1 optional relation with Prisma and MongoDB. I use the following Prisma schema: model User { id String @id @default(auto()) @map("_id") @db.
Risatoga
RisatogaOP9mo ago
Any solution or recommendation for this???
chof64
chof648mo ago
I'm also using MongoDB and is trying to define optional one-to-one relationship and is experiencing the same problem. The second null row, when created returns the error about not being unique. Did you find a solution perhaps, or maybe can share your workaround for this issue. Thanks
Want results from more Discord servers?
Add your server