[英]Firebase 9 get single document from nested collections - React
[英]Get all collections from a document Firebase
您正在很好地構建數據。 問題是Firebase Client SDK
不提供 function 來檢索文檔具有的所有子集合。 為了解決您的問題,您有多種選擇。
1.最干凈但最詳盡的方式
您升級到Blaze 計划並將 Firebase 函數與管理員 SDK 一起使用。 管理員 SDK 提供了一個名為listCollections()
的 function,它完全可以滿足您的需求。 缺點是 Firebase 函數有一個叫做coldstart
啟動的東西,這意味着當你的 function 空閑幾分鍾時,它需要長達 20 秒(根據我的經驗)在你調用它后再次運行,這真的很令人沮喪。 否則,您可以在 Heroku 之類的東西上運行免費的 node.js 服務器來使用管理員 SDK 以避免冷啟動(我認為更好的選擇)。 Admin SDK 明確不打算在客戶端使用。 檢查這個線程
2.列出你所有的待辦事項(最簡單的方法)
每次用戶創建一個新列表時,您都將其添加到用戶文檔中的數組中,如下所示:
// Representation of your user document
user
name: "Florian"
lists: [
"todos",
"anotherList"
]
因此,通過這種方式,您可以獲取您的用戶,從中獲取列表屬性,並在lists
數組上循環調用所有列表。 作為替代方案,只需顯示lists
內容並讓用戶顯式打開它以保存讀取。
3. 重構你的數據庫(我會推薦它)
如果您還沒有大量數據,我建議您重組數據庫,例如:
users - the collection with all your users (without the todo list subcollections
lists - containing a document for every created list
- each document contains a field with `owner`
- each document contains a field with the list name
- each document owns a subcollection with todos
如果您使用這種方式,您可以像這樣查詢數據庫
const getLists = async () => {
const ref = collection(db, 'lists');
const q = query(ref, where('owner', '==', theUserYouWantToQuery);
// returns array with all list (including listname) of that user.
const lists = (await getDocs(q)).docs.map(doc => ({ ...doc.data(), doc.id }));
}
當您擁有該用戶的所有列表對象時,您可以遍歷該數組以獲取列表中的所有待辦事項,或者讓用戶通過打開它只獲取一個列表
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.