[23.12.10] TIL

yy·2023년 12월 10일

개발일지

목록 보기
57/122

(express prisma 이용 중)

자치구별 게시글 목록 조회 시 게시글 내용과 함께 게시글 당 달린 댓글의 개수를 반환해줘야했다.
prisma findMany로 일단 해당 내용을 조회해봤다.

const findPosts = await prisma.posts.findMany({
      where: {
        LocationId: findLocations.LocationId,
      },
      select: {
        imgUrl: true,
        content: true,
        createdAt: true,
        likeCount: true,
        User: {
          select: {
            nickname: true
          }
        },
        Comments: {
          select: {
            content: true // 개수로 반환
          }
        }
      },
      orderBy: {
        createdAt: 'desc'
      },
      take: +limit
    });

findMany에 다른 문법들이 있나 문서를 찾아봤다.
https://www.prisma.io/docs/orm/reference/prisma-client-reference#findmany

...마땅한게 없었다. 조회와 집계를 동시에 할 순 없는건가..
rawquery를 사용해서 해봤다. 조인에 조인을 더했다.

const findPosts =
      await prisma.$queryRaw`select PUC.LocationId, PUC.postId, PUC.imgUrl, PUC.content, PUC.createdAt, PUC.likeCount, PUC.userId, PUC.nickname, PUC.countContent, 
                              DL.districtId, DL.districtName,DL.address
                              from 
                              (
                                SELECT PU.LocationId, PU.postId, PU.imgUrl, PU.content, PU.createdAt, PU.likeCount, PU.userId, PU.nickname, C.countContent 
                                FROM
                                  (
                                    SELECT P.LocationId, P.postId, P.imgUrl, P.content, P.createdAt, P.likeCount, U.userId,U.nickname
                                    FROM posts P JOIN users U ON P.UserId = U.userId
                                  ) PU
                                LEFT JOIN 
                                  (
                                    SELECT postId, count(content) as countContent FROM comments GROUP BY postId
                                  ) C
                                ON PU.postId = C.postId
                              ) PUC
                              left join 
                              (
                                select D.districtId, D.districtName,L.locationId, L.address from districts D right join locations L on
                                D.districtId = L.DistrictId
                              ) DL 
                              on
                              PUC.LocationId = DL.locationId
                              where DL.districtName = ${districtName}
                              group by PUC.postId
                              order by PUC.createdAt DESC 
                              LIMIT ${parsedLimit};`

이렇게까지 조인할 일인가..? 싶어서 조회해야하는 정보들을 최소화했다. 저러고 parsedLimit값을 1부터 하나씩 올려가며 테스트를 해봤다. 그랬더니 7부터 오류가 났다.

TypeError: Do not know how to serialize a BigInt
at JSON.stringify ()

이 에러는 JSON.stringify ()에서 이 부분이 bigInt가 들어가서 발생한거란다.

JSON.stringify()에 bigInt를 포함한 값을 전달하면 typeError가 발생한다고 한다.

JSON 직렬화, 역직렬화

직렬화: 외부의 시스템에서 사용할 수 있도록 데이터 => 바이트 형태로 변환하는 기술.
역직렬화: 반대로 외부 시스템의 바이트 형태의 데이터(Json) => 객체나 해시 테이블, 딕셔너리 등으로 변환


흠 어떻게 하면 좋을지 생각해보다 posts에 commentCount를 넣어주는 방법으로 진행했다. 아무래도 저렇게 긴 rawquery를 사용해서 불안한것보다 컬럼을 새로 만드는게 더 나을것같았다.

profile
시간이 걸릴 뿐 내가 못할 건 없다.

0개의 댓글