CRUD는 데이터를 다루는 4가지 기본 기능의 약자예요.
| 글자 | 뜻 | 설명 | Firestore 예시 함수 |
|---|---|---|---|
| C | Create (생성) | 새로운 데이터를 추가 | addDoc(), setDoc() |
| R | Read (조회) | 데이터를 읽어오기 | getDoc(), getDocs() |
| U | Update (수정) | 기존 데이터를 수정 | updateDoc() |
| D | Delete (삭제) | 데이터를 삭제 | deleteDoc() |
새로운 문서를 추가하는 기능입니다.
import { addDoc, collection } from "firebase/firestore";
import { db } from "../firebase/config.js";
const addBook = async () => {
await addDoc(collection(db, "books"), {
title: "React 입문",
author: "황지원",
price: 30000,
createdAt: new Date()
});
};
🟢 "books"라는 컬렉션에 새로운 도서 문서를 추가하는 코드예요.
데이터를 읽어오는 기능입니다.
import { getDocs, collection } from "firebase/firestore";
import { db } from "../firebase/config.js";
const getBooks = async () => {
const querySnapshot = await getDocs(collection(db, "books"));
querySnapshot.forEach((doc) => {
console.log(doc.id, " => ", doc.data());
});
};
🟢 "books" 컬렉션의 모든 문서를 가져와 콘솔에 출력합니다.
import { doc, updateDoc } from "firebase/firestore";
import { db } from "../firebase/config.js";
const updateBook = async (bookId) => {
await updateDoc(doc(db, "books", bookId), {
price: 35000,
});
};
🟢 "books" 컬렉션 안의 특정 문서(bookId)의 price 필드를 수정합니다.
import { doc, deleteDoc } from "firebase/firestore";
import { db } from "../firebase/config.js";
const deleteBook = async (bookId) => {
await deleteDoc(doc(db, "books", bookId));
};
🟢 "books" 컬렉션 안의 특정 문서를 삭제합니다.
| 기능 | 설명 | Firestore 메서드 |
|---|---|---|
| C - Create | 데이터 추가 | addDoc(), setDoc() |
| R - Read | 데이터 읽기 | getDoc(), getDocs() |
| U - Update | 데이터 수정 | updateDoc() |
| D - Delete | 데이터 삭제 | deleteDoc() |
즉, Firestore나 MySQL, MongoDB 같은 모든 데이터베이스 작업의 기본 패턴이 CRUD예요.
프론트엔드에서도 서버 없이 Firebase를 쓴다면 거의 항상 이 4가지를 구현하게 됩니다.