Firestore - newlife-js/Wiki GitHub Wiki

Firebase

1. 시작

const db = getFirestore();

2. document, collection 접근

const docRef = doc(db, "doc경로");
const docRef2 = doc(docRef1, "collection2/documnet2");

doc경로는 collection/document/collection/document와 같이 짝수개로 이루어져야 함.

const collectionRef = collection(db, "collection경로");

collection경로는 홀수개로 이루어져야 함.

3. doc 추가 및 수정

addDoc(collectionRef, data)
setDoc(docRef, data, {merge:true});

4. doc 읽기

const snapShot = await getDoc(docRef);
if(snapshot.exists()){
  console.log(JSON.stringify(snapShot.data()));
}

쿼리

query = query(
  collection(db, "collection경로"),
  where('필드명', '==', 'value'),
  limit(10)
);
const querySnapshot = await getDocs(query);
querySnapshot.forEach((snap) => {
  console.log(JSON.stringify(snap.data());
}

onSnapshot : document 변경 감지

unsubscribeSnapshot = onSnapshot(docRef, snapshot) => {
  if(snapshot.exists()){
    console.log(JSON.stringify(snapShot.data()));
  }
}

onSnapshot의 리턴값은 함수로, unsubscribe하는 데 쓰임
unsubscribeSnapshot();