Giga Ananidze
Giga Ananidze

Reputation: 13

How to Order by Related Field in Prisma with MongoDB?

I’m using Prisma with MongoDB and have two models: User and Points. Each user can have multiple Points entries. I want to order the users based on the points value in the related Points model.

model User {
  id      String  @id @default(auto()) @map("_id") @db.ObjectId
  name    String
  points  Points[] // A user can have multiple points entries
}

model Points {
  id        String  @id @default(auto()) @map("_id") @db.ObjectId
  points    Int
  category  String  // The category for these points (e.g., "game", "quiz", "purchase")
  userId    String  @db.ObjectId
  user      User    @relation(fields: [userId], references: [id])
}
const users = await prisma.user.findMany({
  include: {
    points: true,
  },
  orderBy: {
    points: {
      points: 'desc',  // Order by the points field in the related Points model (descending order)
    },
  },
});

How can I sort users based on the points field in the Points model?

Upvotes: 0

Views: 52

Answers (0)

Related Questions