Firestore 의 데이터는 Collection(컬렉션) 과 Document(문서) 로 되어있다. Collection > Document 로 되어있는데, 각 문서는 {key: value} 형식으로 들어가있으며 Collection 이 들어가도 된다.
Document 불러오기
하나의 Document 불러오기
const docRef = doc(firestore, 'myCollection', 'doc1');
const docSnap = await getDoc(docRef);
if (docSnap.exists()) {
console.log('Document data:', docSnap.data());
}
모든 Document 불러오기
// 'myCollection' collection 의 모든 document 를 가져오는 방법은?
const q = query(collection(firestore, 'myCollection'));
const querySnapshot = await getDocs(q);
querySnapshot.forEach(doc => {
// doc.data() is never undefined for query doc snapshots
console.log(doc.id, ' => ', doc.data());
});
Document 추가하기
하나의 Document 추가하기
await addDoc(collection(firestore, 'myCollection'), {
name: 'james',
age: '18'
});
Document ID 를 지정 해서 추가하기
addDoc 으로 추가하게되면 ID 가 자동으로 생성된다. 만약 원하는 ID 가 있다면, set 으로 해야 한다.
# 참고로 collection(firestore, 'myCollection') 은
# const ref = collection(firestore, 'myCollection');
# 로 사용하기도 한다.
await setDoc(doc(collection(firestore, 'myCollection'), newId), {
name: 'james',
age: 18
});
참고자료
https://cloud.google.com/firestore/docs/query-data/get-data?hl=ko
https://stackoverflow.com/questions/48541270/how-to-add-document-with-custom-id-to-firestore