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();
CodePudding user response:
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);
}