I have a schema set up where Users can create many Photos, and then attach those photos to a single Post. Other users can repost others' photos, so I need a many to many relation between Photo and Post:
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
photos Photo[]
posts Post[]
...
}
model Photo {
id String @id @default(auto()) @map("_id") @db.ObjectId
user User @relation(fields: [userId], references: [id])
userId String @db.ObjectId
posts Post[] @relation(fields: [postIds], references: [id])
postIds String[] @db.ObjectId
...
}
model Post {
id String @id @default(auto()) @map("_id") @db.ObjectId
poster User @relation(fields: [posterId], references: [id])
posterId String @db.ObjectId
photos Photo[] @relation(fields: [photoIds], references: [id])
photoIds String[] @db.ObjectId
...
}
I am able to create photos and posts just fine, but the problem is when I try to create a new post that connects the existing photos. This is my query:
return await prisma.user.update({
where: {id},
data: {
posts: {
create: {
photoIds,
},
}
}
})
This works for the Posts side of the relation, the Post's photoIds are populated correctly, however the Photo's postIds are left empty. I am not sure how to connect the other side of the relation.
The bizarre thing is that when I do a Post count query on the Photo, it returns the correct count number:
await prisma.user.findUnique({where: { id }}).photos({
where: { id: photoId },
select: {
...
_count: {
select: {
posts: true,
}
},
}
})
This query returns the correct post count for each photo, even though it's postIds list is empty. There must be something simple I am missing here, I have read the Prisma docs on many-to-many relations for MongoDB over and over again but can't seem to figure it out.