I have a data structure of like this.
Now i want to extract from product collection. i am already able to get its fields but don't known how to extract sub collections. Here is my code to extract product collection's field
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();
You would have to make separate requests for each products prices
sub-collection. So you could try something like this:
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.