본문 바로가기
Recap/bookshelf

[에러 해결] Firebase Error: No document to update

by yerin.dev 2024. 2. 25.

Firebase Error

 

 

 

 

bookshelf 프로젝트를 하던 중 발생한 문제. document를 삭제했을 때 이런 오류가 발생했다. 오류에서 친절하게 알려주고 있듯이 document 삭제 후 이미 존재하지 않는(삭제된) document에 접근하고 있다는 것.

 

 

const updateRating = async (isbn13: string, ratingCount: number) => {
    try {
      if (currentUser) {
        const arr: Book[] = [];
        const bookDocRef = doc(db, "users", currentUser, "books", isbn13);
        const querySnapshot = await getDocs(
          collection(db, "users", currentUser, "books")
        );
        querySnapshot.forEach((doc) => {
          arr.push(doc.data() as Book);
        });
        await updateDoc(bookDocRef, { rating: ratingCount });
      }
    } catch (err) {
      console.error(err);
    }
  };

 

 

문제는 updateRating() 함수 때문이었는데,
책(document)을 삭제함 -> firestore onSnapshot 함수 호출 -> 전체 bookList가 변경됨
때문이 아닐까.. 해서 코드를 변경했다.

 

 

문제 해결

 

collection 전체 데이터 중 해당 isbn을 가진 책이 존재하는지 확인하고 존재할 경우에만 updateDoc을 하는 것으로 변경하였다.

 

 

 

const updateRating = async (isbn13: string, ratingCount: number) => {
    try {
      if (currentUser) {
        const arr: Book[] = [];
        const bookDocRef = doc(db, "users", currentUser, "books", isbn13);
        const querySnapshot = await getDocs(
          collection(db, "users", currentUser, "books")
        );
        querySnapshot.forEach((doc) => {
          arr.push(doc.data() as Book);
        });
		
        // isbn이 존재하지 않으면 실행되지 않도록 함.
        if (arr.find((v) => v.isbn13 == isbn13)) await updateDoc(bookDocRef, { rating: ratingCount });
      }
    } catch (err) {
      console.error(err);
    }
  };