[英]Firestore how to extract sub collection from collections
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.
我已经能够获得它的字段,但不知道如何提取子 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.您必须为每个产品
prices
子集合提出单独的请求。 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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.