簡體   English   中英

獲取自動生成的文檔 ID 以創建文檔或更新文檔 Firestore / Firebase 中的數組的更好方法

[英]Better way to get document ID which was auto generated to create the doc or update an array inside the document Firestore / Firebase

我正在為每個用戶創建一個文檔來存儲用戶書簽的 ID。 我正在使用 addDoc,因此創建的文檔的 ID 由 firebase 生成。我想檢查該文檔是否存在以創建新文檔或更新舊文檔。 我需要一個文檔參考來更新文檔,我花了很長時間試圖找出一種方法來獲取自動生成的 ID。 我的代碼有效,但感覺真的很糟糕 - 有沒有更好的方法來完成這個?

//Add a value to the bookmarks array for individual user
export const addBookmarkForUser = async (userAuth, showId) => {
  const bookmarkDocRef = collection(db, 'users', userAuth.uid, 'bookmarks')
  const bookmarkSnapshot = await getDocs(bookmarkDocRef)
  let userBookmarkDocId
  if(bookmarkSnapshot){   
    bookmarkSnapshot.forEach((doc) => {
      if(doc.id){
        userBookmarkDocId = doc.id
        console.log(userBookmarkDocId)
      }
    })    
  }  
  try {    
    if(!bookmarkSnapshot) {
      await addDoc((collection(db, 'users', userAuth.uid, 'bookmarks'), {
        favorites: [{showId: showId}],
      }))
    }else {
      const userBookmarkRef = doc(db, 'users', userAuth.uid, 'bookmarks', userBookmarkDocId)
      await updateDoc(userBookmarkRef, {
        favorites: arrayUnion({showId: showId})
      })}
    
  } catch (error) {
    console.log('Error creating bookmark', error.message);
  }
};

我知道我只會為每個用戶提供一個文檔 - 是否有更好的方法來查找 doc.id?

這是 Firestore 結構 - firestore1

firestore2

如果您只想檢查集合中有多少文檔,那么您可以使用getCountFromServer()來加載計數而不需要實際的文檔數據。

import { collection, getCountFromServer } from 'firebase/firestore';

const bookmarkColRef = collection(db, 'users', userAuth.uid, 'bookmarks');
const bookmarksCount = (await getCountFromServer(bookmarksColRef)).data().count

console.log(`${bookmarksCount} documents found in ${bookmarksColRef.path}`)\

if (!bookmarksCount) {
  // no document exists, create new 
}

但是,由於您需要文檔 ID 及其數據。 您可以運行一個簡單的查詢:

import { collection, getDocs } from 'firebase/firestore';

const bookmarkColRef = collection(db, 'users', userAuth.uid, 'bookmarks');
const bookmarksSnap = await getDocs(bookmarksColRef);

if (bookmarksSnap.empty()) {
  // no document
} else {
  const docData = bookmarksSnap.docs[0].data();
  console.log(docData)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM