我有一個這樣的資料結構。

現在我想從產品集合中提取。我已經能夠獲取它的欄位,但不知道如何提取子集合。這是我提取產品集合欄位的代碼
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();
uj5u.com熱心網友回復:
您必須對每個產品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);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/400022.html
