myBlog는 서버 없이 강력한 웹/모바일 앱을 개발할 수 있는 Firestore를 클라우드 데이터베이스로 사용합니다.
Cloud Firestore는 Google Firebase에서 제공하는 NoSQL 클라우드 데이터베이스 입니다.
Firestore란?
Cloud Firestore는 Google Firebase에서 제공하는 NoSQL 클라우드 데이터베이스로,
실시간 데이터 동기화 및 확장성 높은 데이터 관리를 지원합니다.
특히 Firebase Authentication, Firebase Functions, Firebase Hosting 등과 쉽게 연동할 수 있어,
웹 & 모바일 앱 개발에 많이 사용됩니다.
Firestore의 주요 특징
1. NoSQL 문서 기반 데이터베이스
- 테이블이 아닌 컬렉션(Collection)과 문서(Document) 구조를 사용
- 관계형 데이터베이스(SQL)와 달리 JSON 형태로 데이터를 저장
- 스키마가 유연하여 동적으로 데이터 필드를 추가 가능
2. 실시간 동기화 (Realtime Sync)
- 데이터 변경이 즉시 반영됨 (앱에서 데이터를 자동으로 업데이트 가능)
- onSnapshot()을 사용하면 데이터 변경을 실시간 감지
3. 서버리스 & 확장성
- 백엔드 서버 없이 클라우드에서 데이터 관리
- 자동 확장(Auto Scaling) 기능 제공 (사용량에 따라 확장 및 축소)
4. 강력한 보안 (Security Rules)
- Firestore 보안 규칙(Firebase Security Rules) 을 사용하여 데이터 접근 제어
예: 특정 사용자만 읽기/쓰기 가능하도록 설정
5. 간편한 데이터 쿼리
- where() 및 orderBy()를 사용하여 복잡한 쿼리 수행 가능
예: 특정 날짜 이후의 데이터만 가져오기
Firestore 데이터 구조
기본 개념
Firestore는 컬렉션(Collection) → 문서(Document) → 필드(Field) 계층 구조를 가짐
📂 posts (Collection)
├── 📄 post1 (Document)
│ ├── title: "Vue와 Firestore"
│ ├── content: "Firestore를 Vue에서 사용하는 방법"
│ ├── createdAt: Timestamp
├── 📄 post2 (Document)
│ ├── title: "Firebase Authentication"
│ ├── content: "Google 로그인 구현 방법"
│ ├── createdAt: Timestamp
- 컬렉션(Collection): 여러 개의 문서를 포함하는 그룹
- 문서(Document): JSON 객체처럼 데이터를 저장하는 단위
- 필드(Field): 문서 내부에 저장되는 개별 데이터
Firestore 사용법 (CRUD)
1. Firestore 연결
Firebase 프로젝트를 설정하고 Firestore를 사용하려면 Firebase SDK를 설치해야 합니다.
npm install firebase
Firestore를 초기화하는 코드:
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_PROJECT.firebaseapp.com",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_PROJECT.appspot.com",
messagingSenderId: "SENDER_ID",
appId: "APP_ID",
};
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
2. Firestore에서 데이터 추가 (Create)
Firestore에 새 문서를 추가하려면 addDoc() 또는 setDoc()을 사용합니다.
import { collection, addDoc } from "firebase/firestore";
const addPost = async () => {
try {
await addDoc(collection(db, "posts"), {
title: "Firestore 배우기",
content: "Vue에서 Firestore CRUD 연습",
createdAt: new Date(),
});
console.log("문서 추가 성공");
} catch (error) {
console.error(" 문서 추가 실패:", error);
}
};
3. Firestore에서 데이터 읽기 (Read)
단일 문서 가져오기
import { doc, getDoc } from "firebase/firestore";
const getPost = async (postId) => {
const docRef = doc(db, "posts", postId);
const docSnap = await getDoc(docRef);
if (docSnap.exists()) {
console.log("문서 데이터:", docSnap.data());
} else {
console.log("문서 없음");
}
};
여러 문서 가져오기
import { collection, getDocs } from "firebase/firestore";
const getPosts = async () => {
const querySnapshot = await getDocs(collection(db, "posts"));
querySnapshot.forEach((doc) => {
console.log(`문서 ID: ${doc.id}`, doc.data());
});
};
4. Firestore에서 데이터 업데이트 (Update)
Firestore 문서의 특정 필드를 업데이트하려면 updateDoc()을 사용합니다.
import { doc, updateDoc } from "firebase/firestore";
const updatePost = async (postId) => {
const docRef = doc(db, "posts", postId);
try {
await updateDoc(docRef, {
title: "업데이트된 Firestore 제목",
});
console.log("문서 업데이트 성공");
} catch (error) {
console.error("문서 업데이트 실패:", error);
}
};
5. Firestore에서 데이터 삭제 (Delete)
Firestore 문서를 삭제하려면 deleteDoc()을 사용합니다.
import { doc, deleteDoc } from "firebase/firestore";
const deletePost = async (postId) => {
try {
await deleteDoc(doc(db, "posts", postId));
console.log("문서 삭제 성공");
} catch (error) {
console.error("문서 삭제 실패:", error);
}
};
Firestore 실시간 데이터 감지
Firestore의 강력한 기능 중 하나는 실시간 데이터 감지입니다.
onSnapshot()을 사용하면 데이터 변경을 즉시 감지하고 업데이트할 수 있습니다.
import { collection, onSnapshot } from "firebase/firestore";
const listenForPosts = () => {
onSnapshot(collection(db, "posts"), (snapshot) => {
snapshot.docChanges().forEach((change) => {
if (change.type === "added") {
console.log("추가된 문서:", change.doc.data());
}
if (change.type === "modified") {
console.log("수정된 문서:", change.doc.data());
}
if (change.type === "removed") {
console.log("삭제된 문서:", change.doc.id);
}
});
});
};
Firestore 보안 규칙 설정
Firestore는 보안 규칙을 통해 읽기 및 쓰기 권한을 설정할 수 있습니다.
예를 들어, 로그인한 사용자만 데이터를 읽고 쓸 수 있도록 설정하려면:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /posts/{postId} {
allow read, write: if request.auth != null;
}
}
}
정리
- Firestore는 NoSQL 문서 기반 클라우드 데이터베이스
- 컬렉션(Collection) → 문서(Document) → 필드(Field) 구조
- 실시간 데이터 감지 기능(onSnapshot) 제공
- Firebase Authentication과 쉽게 연동 가능
- Firestore 보안 규칙을 통해 데이터 접근 제어 가능