簡體   English   中英

如何在 Firebase / Firestore 中創建用戶時創建嵌套集合,用戶可以在其中保存已添加書簽的項目

[英]How to create a nested collection when creating a user in Firebase / Firestore where users can save bookmarked items

我希望能夠在 firebase/firestore 中有一個嵌套集合,我可以在其中保存經過身份驗證的用戶的收藏夾。 我試圖在創建用戶時創建集合,以便稍后可以讀取/寫入它,但我不知道如何創建集合。 我有這樣的事情:

//This function creates a new user. If the user already exists, no new document will be created
export const createUserDocumentFromAuth = async (
  userAuth,
  additionalInfo = {}
) => {
  if (!userAuth) return;

  const userDocRef = doc(db, 'users', userAuth.uid); //database instance, collection, identifier
  const bookmarkRef = doc(db, 'users', userAuth.id, 'bookmarks'); //This triggers error
  const userSnapshot = await getDoc(userDocRef);
  if (!userSnapshot.exists()) {
    //If user snapshot doesn't exist - create userDocRef
    const { displayName, email } = userAuth;
    const createdAt = new Date();

    try {
      await setDoc(userDocRef, {
        displayName,
        email,
        createdAt,
        ...additionalInfo,
      });
      setDoc(bookmarkRef, { //Try to create a bookmarks collection here
        favorites: []
      })
    } catch (error) {
      console.log('Error creating user', error.message);
    }
  }
  //if user data exists
  return userDocRef;
};

我可以很好地創建用戶,但不能同時創建另一個集合。 我也嘗試過在登錄用戶像這樣單擊書簽按鈕時創建集合,但在這兩種情況下我都會收到類型錯誤Uncaught (in promise) TypeError: n is undefined每次。

export const addBookmarkForUser = async (userAuth, showId) => {
  const bookmarkRef = doc(db, 'users', userAuth.id, 'bookmarks');
  try {
    await setDoc(bookmarkRef, {
      favorites: showId
    });
  }catch(error){
    console.log('error creating bookmark', error.message)
  } 
};

我是 Firebase / Firestore 的新手,我想要的只是能夠在單個用戶單擊按鈕時將項目 ID 保存在數組中。 如果保存在數組中並不理想或者有任何更好的方法來執行此操作,我現在願意接受任何建議。

我試圖在創建用戶時創建集合,以便稍后可以讀取/寫入它,但我不知道如何創建集合。

(子)集合僅在您在其中創建第一個文檔時創建 沒有文檔就無法具體空集合。

而且使用doc()方法報錯是正常的,如下

const bookmarkRef = doc(db, 'users', userAuth.id, 'bookmarks');

因為此方法用於創建DocumentReference ,因此您需要傳遞具有偶數個路徑段的路徑。 在你的情況下,你傳遞了 3 個部分。

您可以很好地為bookmarks子集合定義CollectionReference ,如下所示,使用collection()方法並傳遞 3 個段

const bookmarkRef = collection(db, 'users', userAuth.id, 'bookmarks');

但是,除非您在其中添加文檔,否則它不會存在於數據庫中。


結論:您將在第一次為用戶創建書簽時自動創建用戶的bookmarks子集合。

例如:

const bookmarksCollectionRef = collection(db, 'users', userAuth.id, 'bookmarks');
await bookmarksCollectionRef.add({ ... })

暫無
暫無

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

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