[英]What is the most efficient way to get all documents from multiple sub-collections of multiple sub-collections in Firestore?
[英]Read documents in the sub-collections of a document firestore (V9 (Modular))
我有一組用戶。 該集合中的每個文檔都包含用戶數據。 在該文檔中,有關於他們的用戶名、簡歷等的信息。此外,在用戶文檔中還有一個名為 posts 的子集合。 posts 中的每個文檔都是用戶發布的一個單獨的帖子。
目前,我的程序正在讀取實時更新以檢查用戶名和簡歷的變化。 但是,我希望它還檢查帖子集合中的實時更新,看看是否有新帖子。 這樣它就知道在用戶配置文件中顯示新帖子。
這是我當前用於檢查更新的代碼:
const [name, setName] = useState('');
const [bio, setBio] = useState('');
// Post title
const [p_title, setP_title] = useState('');
// Hears for when there's been an update
useEffect(() => {
const unsubscribe = onSnapshot(doc(db, "usrs", usrUID), (doc) => {
setName(doc.data().name);
setBio(doc.data().bio);
console.log(doc.data());
});
// Unsubscribe stops it from listening when it shouldn't
return unsubscribe
}, []);
我希望有某種類型的東西:
doc.data().collection("Posts").posts.title
或類似的東西,以便我可以列出子集合中帖子的標題,以及名稱和簡介。
我對 React native 和 firestore 很陌生。 我常常覺得我正在使用不同版本的大量信息。
任何幫助,將不勝感激!
一個onSnapshot()
只能偵聽給定文檔或集合的更新。 因此,對於用戶的帖子,您需要另一個偵聽器。 嘗試:
// Listen for user document updates
const unsubUserDoc = onSnapshot(doc(db, "usrs", usrUID), (doc) => {
setName(doc.data().name);
setBio(doc.data().bio);
console.log(doc.data());
});
// Listen for user's post changes
const unsubPostsCol = onSnapshot(collection(db, "usrs", usrUID, "posts"), (querySnap) => {
console.log(querySnap.docs.map((d) => ({
id: d.id,
...d.data()
})));
// set all docs in state
});
每次創建/更新/刪除用戶的帖子時都會觸發第二個偵聽器。 這也將在初始化后獲取所有帖子,因此最好盡可能對結果進行分頁。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.