npm install firebase@10.7.1 --saveyarn add firebaseimport { initializeApp } from "firebase/app";import { getFirestore } from "firebase/firestore";import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
// TODO: Replace the following with your app's Firebase project configuration
// See: https://support.google.com/firebase/answer/7015592
const firebaseConfig = {
FIREBASE_CONFIGURATION
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
// Initialize Cloud Firestore and get a reference to the service
const db = getFirestore(app);
단일 문서를 만들거나 덮어쓰려면 다음 언어별
set()메서드를 사용한다.
import { doc, setDoc } from "firebase/firestore";
// Add a new document in collection "cities"
await setDoc(doc(db, "cities", "LA"), {
name: "Los Angeles",
state: "CA",
country: "USA"
});
문서가 없으면 생성된다.
문서가 있으면 새로 제공한 데이터로 덮어쓰는데, 다음과 같이 데이터를 기존 문서와 병합하도록 지정한 경우는 예외.
import { doc, setDoc } from "firebase/firestore";
const cityRef = doc(db, 'cities', 'BJ');
setDoc(cityRef, { capital: true }, { merge: true });
Cloud Firestore를 사용하면 문서 안에 문자열, 불리언, 숫자, 날짜, null, 중첩 배열, 객체를 비롯하여 다양한 데이터 유형을 쓸 수 있다.
Cloud Firestore는 코드에서 사용하는 숫자 유형과 관계없이 숫자를 항상 배정밀도 부동 소수점으로 저장한다.
import { doc, setDoc, Timestamp } from "firebase/firestore";
const docData = {
stringExample: "Hello world!",
booleanExample: true,
numberExample: 3.14159265,
dateExample: Timestamp.fromDate(new Date("December 10, 1815")),
arrayExample: [5, true, "hello"],
nullExample: null,
objectExample: {
a: 5,
b: {
nested: "foo"
}
}
};
await setDoc(doc(db, "data", "one"), docData);
전체 문서를 덮어쓰지 않고 문서의 일부 필드를 업데이트하려면 다음과 같은 언어별 update()메서드를 사용한다.
import { doc, updateDoc } from "firebase/firestore";
const washingtonRef = doc(db, "cities", "DC");
// Set the "capital" field of the city 'DC'
await updateDoc(washingtonRef, {
capital: true
});
문서의 필드를 서버 업데이트 수신 시점을 추적하는 서버 타임스탬프로 설정할 수 있다.
import { updateDoc, serverTimestamp } from "firebase/firestore";
const docRef = doc(db, 'objects', 'some-id');
// Update the timestamp field with the value from the server
const updateTimestamp = await updateDoc(docRef, {
timestamp: serverTimestamp()
});
문서에 중첩된 객체가 있으면 update()를 호출할 때, '점 표기법'을 사용하여 문서 내 중첩 필드를 참조할 수 있다.
import { doc, setDoc, updateDoc } from "firebase/firestore";
// Create an initial document to update.
const frankDocRef = doc(db, "users", "frank");
await setDoc(frankDocRef, {
name: "Frank",
favorites: { food: "Pizza", color: "Blue", subject: "recess" },
age: 12
});
// To update age and favorite color:
await updateDoc(frankDocRef, {
"age": 13,
"favorites.color": "Red"
});
다음 예시와 같이 숫자 필드 값을 늘리거나 줄일 수 있다.
증분 작업은 필드의 현재 값을 지정된 값만큼 늘리거나 줄인다.
import { doc, updateDoc, increment } from "firebase/firestore";
const washingtonRef = doc(db, "cities", "DC");
// Atomically increment the population of the city by 50.
await updateDoc(washingtonRef, {
population: increment(50)
});
하지만 이 역시 견고하고 안전하게 구현해야할 부분이기에 최선을 다 해야할 것 같다.