Prisma, Can't use '_count' in 'FindMany' query to get total count of the data

Viewed 87
const fictions = await client.fiction.findMany({
      **_count: true,**
      take: 18,
      skip: (+page!.toString() - 1 || 0) * 18,
      where: {
        AND: [
          { OR: [...genresMany] },
          {
            OR: [...nationalitiesMany],
          },
          {
            AND: [...keywordMany],
          },
        ],
      },
      include: {
        _count: {
          select: {
            favs: true,
          },
        },
        author: true,
      },
      ...sortingOne(),
    });

I'd like to get total count of the query for pagination. And the manual says the using _count is the way.

However, it seems _count cannot be used in the query, and I can't find out the reason.

Is it a wrong usage?

If it's wrong, then what can I do for getting the total count of the query (not 18, the taked items)?

Should I count them again with the similar code after the query? I think that's too wasteful.

Would be very thanks if there's any help.

1 Answers

there should be a top-level count method for your model. You could that first to just return a count, that request should be fast and cheap since it has to do no sorting / fetching of data. And then you can do a separate call to actually return data and paginate through it.

const fictions = await client.fiction.count({
      where: {
        AND: [
          { OR: [...genresMany] },
          {
            OR: [...nationalitiesMany],
          },
          {
            AND: [...keywordMany],
          },
        ],
      }
    });
Related