CRUD

joy·2025년 11월 4일

firebase

목록 보기
4/4

🔹 CRUD란?

CRUD데이터를 다루는 4가지 기본 기능의 약자예요.

글자설명Firestore 예시 함수
CCreate (생성)새로운 데이터를 추가addDoc(), setDoc()
RRead (조회)데이터를 읽어오기getDoc(), getDocs()
UUpdate (수정)기존 데이터를 수정updateDoc()
DDelete (삭제)데이터를 삭제deleteDoc()

🔹 Firestore 기준으로 CRUD 예시

1️⃣ Create (생성)

새로운 문서를 추가하는 기능입니다.

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"라는 컬렉션에 새로운 도서 문서를 추가하는 코드예요.


2️⃣ Read (조회)

데이터를 읽어오는 기능입니다.

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" 컬렉션의 모든 문서를 가져와 콘솔에 출력합니다.


3️⃣ Update (수정)

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 필드를 수정합니다.


4️⃣ Delete (삭제)

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가지를 구현하게 됩니다.

profile
FE

0개의 댓글