9.5.1 Firestore 데이터 조회할 때 조건 추가하기

    특정 조건을 걸어 포스트를 조회할 때는 다음과 같이 where 함수를 사용합니다.

    const snapshot = await postsCollection
      .where('user.id', '==', userId)
      .orderBy('createdAt', 'desc')
      .limit(PAGE_SIZE)
      .get();

    이와 같이 코드를 작성하면 포스트 중에서 user 객체의 id 값이 userId인 포스트들을 조회하게 됩니다.

    기존에 구현한 함수에 userId라는 파라미터를 추가하고, 만약 이 파라미터가 존재하면 where를 사용하도록 함수들을 수정해보겠습니다.

    lib/posts.js - getPosts, getOlderPosts, getNewerPosts

    export async function getPosts(userId) {
      let query = postsCollection.orderBy('createdAt', 'desc').limit(PAGE_SIZE);
      if (userId) {
        query = query.where('user.id', '==', userId);
      }
      const snapshot = await query.get();
    
      const posts = snapshot.docs.map((doc) => ({
        id: doc.id,
        ...doc.data(),
      }));
    
      return posts;
    }
    
    export async function getOlderPosts(id, userId) {
      const cursorDoc = await postsCollection.doc(id).get();
      let query = postsCollection
        .orderBy('createdAt', 'desc')
        .startAfter(cursorDoc)
        .limit(PAGE_SIZE);
      if (userId) {
        query = query.where('user.id', '==', userId);
      }
      const snapshot = await query.get();
    
      const posts = snapshot.docs.map((doc) => ({
        id: doc.id,
        ...doc.data(),
      }));
    
      return posts;
    }
    
    export async function getNewerPosts(id, userId) {
      const cursorDoc = await postsCollection.doc(id).get();
        let query = postsCollection
          .orderBy('createdAt', 'desc')
          .endBefore(cursorDoc)
          .limit(PAGE_SIZE);
      if (userId) {
        query = query.where('user.id', '==', userId);
      }
      const snapshot = await query.get();
    
      const posts = snapshot.docs.map((doc) => ({
        id: doc.id,
        ...doc.data(),
      }));
    
      return posts;
    }

    let으로 query를 미리 선언하고, 만약 userId가 존재하면 where 함수를 사용하도록 구현해줬습니다.

    신간 소식 구독하기
    뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.