簡體   English   中英

Firestore 如何從 collections 中提取子集合

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM