'Prisma order posts based on likes

I have a Post model:

model Post {
  id      String @id @default(auto()) @map("_id") @db.ObjectId
  title   String
  content String
  likes   Like[]
}

And a Like model:

model Like {
  id        String   @id @default(auto()) @map("_id") @db.ObjectId
  user      User     @relation(fields: [userId], references: [id])
  userId    String   @db.ObjectId
  postId    String   @db.ObjectId
  post      Post     @relation(fields: [postId], references: [id])
  likeType  LikeType
}

enum LikeType {
  like
  dislike
}

I want to order posts based on the number of Likes (not dislikes) a post receives. Something like:

prisma.post.findMany({
    orderBy: {
      likes: {
        _count: {
          where: {
            likeType: "like",
          }
        }
      }
    }
  })


Solution 1:[1]

You can sort by a relation from 2.19.0 by aggregates including count. But it's currently not possible to return the count of a relation itself. Separating the models for likes and dislikes simplifies the query pattern.

const orderedPosts = await prisma.post.findMany({
  orderBy: {
    likes: {
      count: 'asc'
    }
  }
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1