study: 리네다기 | 9장 - Firestore (get, orderBy. startAfter, endBefore, remove)

Lumpen·2023년 5월 16일
0

Study

목록 보기
84/92

firestore 컬렉션의 get() 함수를 호출하면
해당 컬렉션의 QuerySanpshot 객체가 반환된다
QuerySanpshot 객체 내부에 docs 라는 배열 내부에 각 문서에 대한 정보가 들어있다

조회 결과가 없다면 빈 배열을 반환한다

docs 배열은 고유 id 값이 존재하지 않는다

odrderBy 함수를 통해 데이터를 정렬할 수 있다

Firestore에서 색인 추가하기

특정 사용자의 포스트를 조회하는 과정에서 
user.id를 찾아서 조회하고 
createdAt을 내림차순으로 정렬하고 있는데, 
이렇게 특정 조건이 붙고 특정 속성으로 정렬할 때는 
Firestore에서 색인(index)을 추가해야 합니다.

Firebase 콘솔 페이지의 사이드바에서 
Firestore Database를 선택하고, 
상단에서 색인을 선택합니다. 그리고 색인 만들기를 누르세요.

export async function getPosts() {
  const snapshot = await postsCollection.orderBy('createdAt', 'desc').get();

  const posts = snapshot.docs.map((doc) => ({
    id: doc.id,
    ...doc.data(),
  }));

  return posts;
}

endBefore 함수를 사용하면 목록을 불러온 시점 이후에 추가된 데이터를 불러온다

endBefore 를 startAfter 로 변경하면 limit 이후의 데이터를 limit 만큼 가져온다

export async function getNewerPosts(id) {
  const cursorDoc = await postsCollection.doc(id).get();
  const snapshot = await postsCollection
    .orderBy('createdAt', 'desc')
    .endBefore(cursorDoc)
    .limit(PAGE_SIZE)
    .get();

  const posts = snapshot.docs.map((doc) => ({
    id: doc.id,
    ...doc.data(),
  }));

  return posts;
}

Firestore에서 데이터를 삭제
posts에서 특정 id를 가진 문서를 삭제 시 다음과 같이 작성한다

export function removePost(id) {
  return postsCollection.doc(id).delete();
}

데이터 수정 시에는 다음과 같이 작성한다

firestore()
  .collection('posts')
  .doc(id)
  .update({
    description: 'hello world'
});
profile
떠돌이 생활을 하는. 실업자는 아니지만, 부랑 생활을 하는

0개의 댓글