Prisma.js mongodb relation filter doesn't work

I have a model Post that looks like this:

model Post {
  id        String   @id @default(auto()) @map("_id") @db.ObjectId
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
...
...
...

  LikedPosts LikedPost[]
}

and model LikedPost that looks like this:

model LikedPost {
  id        String   @id @default(auto()) @map("_id") @db.ObjectId
  createdAt DateTime @default(now())

  post   Post @relation(fields: [postId], references: [id])
  postId String
  user            User          @relation(fields: [userId], references: [id])
  userId          String

  @@unique([userId, postId])
}

I'm trying to return all posts that user liked inside db.post.findMany with this prisma filter:

where: {
  LikedPosts: {
    some: {
      userId: {
        equals: session.userId as string,
      },
    },
  },
},

But it always returns empty array as a result.

Even if I put raw value instead of session.userId like "62d6b8d220ba0fa6d5cea60f" of the user that has liked posts, it still returns nothing. It doesn't even work inside Prisma Studio. Am I doing something wrong here?

Upvotes: 2

Views: 583

Answers (1)

The answer was to add @db.ObjectId to the userId field in prisma Schema like this:

model LikedPost {
  id        String   @id @default(auto()) @map("_id") @db.ObjectId
  createdAt DateTime @default(now())

  post   Post @relation(fields: [postId], references: [id])
  postId          String        @db.ObjectId
  user            User          @relation(fields: [userId], references: [id])
  userId          String        @db.ObjectId

  @@unique([userId, postId])
}

Upvotes: 2

Related Questions