![](/img/trans.png)
[英]How to delete a collection with all its sub-collections and documents from Cloud Firestore
[英]Firestore how to extract sub collection from collections
我有這樣的數據結構。
現在我想從產品集合中提取。 我已經能夠獲得它的字段,但不知道如何提取子 collections。 這是我提取產品集合字段的代碼
useEffect(() => { async function fetchData() { const conditional_fetch = query( collection(db, "products"), where("active", "==", true) ); const querySnapshot = await getDocs(conditional_fetch); const products = []; querySnapshot.forEach((doc) => { products[doc.id] = doc.data(); }); setProducts(products); } fetchData();
您必須為每個產品prices
子集合提出單獨的請求。 所以你可以嘗試這樣的事情:
async function fetchData() {
// 1. Fetching products
const conditional_fetch = query(
collection(db, "products"),
where("active", "==", true)
);
const querySnapshot = await getDocs(conditional_fetch);
const products = [];
// 2. For each product, fetching documents from prices sub-collection
for (const doc of querySnapshot.docs) {
const prices = await getDocs(
collection(doc.ref, "prices", "timestamp", "desc")
);
products.push({
id: doc.id,
...doc.data(),
prices: prices.docs.map(p => p.data())
});
}
setProducts(products);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.