TIL_001 | 팀 프로젝트 시작

묘한묘랑·2023년 11월 27일
0

TIL

목록 보기
1/31

FireStore

Firebase의 FireStore의 함수들에 대하여 학습을 진행하였다.

가져오기

// Init 한 Db를 통하여 "cities" 라는 이름의 Collection에 대한 정보를 담게 한다.
const citiesRef = collection(db, "cities");

/**
* doc(CollectionRef, '지정할 Document의 Name')
* setDoc(doc, Data);
*/
await setDoc(doc(citiesRef, "SF"), {
    name: "San Francisco", state: "CA", country: "USA",
    capital: false, population: 860000,
    regions: ["west_coast", "norcal"] });

await setDoc(doc(citiesRef, "LA"), {
    name: "Los Angeles", state: "CA", country: "USA",
    capital: false, population: 3900000,
    regions: ["west_coast", "socal"] });

await setDoc(doc(citiesRef, "DC"), {
    name: "Washington, D.C.", state: null, country: "USA",
    capital: true, population: 680000,
    regions: ["east_coast"] });

await setDoc(doc(citiesRef, "TOK"), {
    name: "Tokyo", state: null, country: "Japan",
    capital: true, population: 9000000,
    regions: ["kanto", "honshu"] });

await setDoc(doc(citiesRef, "BJ"), {
    name: "Beijing", state: null, country: "China",
    capital: true, population: 21500000,
    regions: ["jingjinji", "hebei"] });

// 위와 같은 데이터를 넣은 상태이다.
---
/**
* doc(db, "Collection의 Name", "Document의 Name")
*/
const docRef = doc(db, "cities", "SF");
const docSnap = await getDoc(docRef);

// .exists() - Data가 존재하면 true 아니면 false를 반환한다.
if (docSnap.exists()) {
  console.log("Document data:", docSnap.data());
} else {
  // docSnap.data() will be undefined in this case
  console.log("No such document!");
}

---

// query 함수를 이용하여 특정 데이터만 가져오는 것도 가능하다.
// collection(db, "CollectionName") - sql문의 from절 역할을 한다.
const q = query(collection(db, "cities"), where("capital", "==", true));
// 해당되는 documents를 반환한다.
await getDocs(q)
  

위 케이스로 알 수 있는 것은 doc 함수의 반환 값은, 얻고자 하는 데이터의 위치를 가지고 있는 데이터인것 같다. (편지 봉투를 떠올리면 이해하기 편하다 생각된다.)
이후 함께 사용하는 get 또는 set을 이용하여 그 데이터를 doc 함수의 반환 값에 해당하는 위치에 저장 또는 읽어 오는 것처럼 보인다.

Reference - 데이터 가져오기 공식 문서

profile
상황에 맞는 기술을 떠올리고 사용할 수 있는 개발자가 되고 싶은 개발자

0개의 댓글