나의 개발일지

[React/TypeScript] 최종프로젝트 - Mango(환경오염 줄이기 / 지구 살리기 프로젝트!) (진행 중) - Firebase addDoc과 setDoc의 차이 / 프로필 수정 본문

과제 및 팀프로젝트

[React/TypeScript] 최종프로젝트 - Mango(환경오염 줄이기 / 지구 살리기 프로젝트!) (진행 중) - Firebase addDoc과 setDoc의 차이 / 프로필 수정

heew0n 2024. 1. 10. 15:11

로그인을 하면 Authentication 뿐만 아니라 Firebase DB에 저장해야 했다.

user의 uid를 통해 다른 페이지에서도 활용해야 했기 때문이다.

 

그래서 단순히 addDoc을 사용했는데 문제점이 발견되었다.

 

내가 원했던 것은 users 컬렉션의 문서 이름이 uid로 저장이 되어서

uid로 간편하게 정보를 불러오고 싶었던 건데 addDoc으로 여러 방법을 시도해봤지만 되지 않았다.

열심히 서칭해본 결과 setDoc을 사용하면 된다는 것을 알게 되었다.

 

그럼 addDoc과 setDoc의 차이점이 뭘까?

 

 

 

 

우선 공식 문서를 살펴보자.

https://firebase.google.com/docs/firestore/manage-data/add-data?hl=ko

 

Cloud Firestore에 데이터 추가  |  Firebase

Firebase 데모 데이가 시작되었습니다. Google 최고의 기술을 활용하여 AI 기반 풀 스택 앱을 빌드하고 성장시키는 방법에 관한 데모를 시청하세요. 의견 보내기 Cloud Firestore에 데이터 추가 컬렉션을

firebase.google.com

 

 

 

#addDoc

import { collection, addDoc } from "firebase/firestore"; 

// Add a new document with a generated id.
const docRef = await addDoc(collection(db, "cities"), {
  name: "Tokyo",
  country: "Japan"
});
console.log("Document written with ID: ", docRef.id);

 

addDoc은 문서에 유의미한 ID를 두지 않고 Cloud Firestore에서 자동으로 ID를 생성한다고 한다

 

 

 

#setDoc

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"
});

 

 

그러나 set()을 사용하여 문서를 만들 때는 만들 문서의 ID를 지정해야 한다고 한다.

 

 

즉, addDoc은 문서가 생성될 때 ID가 랜덤으로 생성이 되고

setDoc은 ID를 지정하여 생성할 수 있다.

그래서 나는 문서의 ID를 user의 uid로 저장했다!

 

 

const userId = auth.currentUser?.uid;

if (userId) {
        await setDoc(doc(db, 'users', userId), {
          userEmail: auth.currentUser?.email,
          displayName: auth.currentUser?.displayName,
          profileImg: auth.currentUser?.photoURL,
          uid: auth.currentUser?.uid,
          // phoneNumber: auth.currentUser?.phoneNumber,
          role: 'user'
        });
      }