내일배움캠프

230721 javascript query firestore with doucumentId

Neda 2023. 7. 21. 20:01

230721 파이어베이스에서 doument id 값을 이용해 쿼리하는 방법

doucumentId()와 where in... 을 사용하면 반복문을 통해 getDoc()를 하지 않아도 한 번에 doumentId값을 사용해 여러 문서를 가져올 수 있다.

 

https://firebase.google.com/docs/reference/js/firestore_?hl=ko#documentid 

 

@firebase/firestore  |  Firebase JavaScript API reference

 

firebase.google.com

import { collection, documentId, getDocs, query, where } from 'firebase/firestore';

const getPosts = async (idsArray) => {
  const q = query(collection(db, 'posts'), where(documentId(), 'in', idsArray));
  const querySnapshot = await getDocs(q);
  const posts = [];
  querySnapshot.forEach((doc) => {
    stores.push({ id: doc.id, ...doc.data() });
  });
  return posts;
};