【问题标题】:Why can't I get the sub-collection items in firebase in react in 2022为什么我在 2022 年的 react 中无法获取 firebase 中的子收藏项
【发布时间】:2022-11-10 13:54:59
【问题描述】:

所以我一直在研究如何获得 firebase 文档的子集。基本上是它的.get(),但它现在在 2022 年不起作用我认为.我有下面的代码...

假设这个我将创建一个包含集合的子集合路径。

await setDoc(doc(db,list2[i],`${currentUser?.email}-${uid}`,`single_item`,`image`),{
    creator:username,name:name,img:downloadURL,email:currentUser?.email
})

await setDoc(doc(db,list2[i],`${currentUser?.email}-${uid}`,`group_item`,`images`),{
    creator:username,name:name,img:downloadURL,email:currentUser?.email
})

现在我用这些来获取所有的firebase文件项目......

export const owneritemsRef = collection(db,'owner_items')
export const singleItemsRef = collection(db,'owner_items/single_item/image')
export const groupItemsRef = collection(db,'owner_items','group_item',`images`)

现在当我试图在我的反应文件中阅读它时......

  useEffect(() => {
    console.log(singleItemsRef)
    const unsubscribe = onSnapshot(singleItemsRef,snapshot => {
      console.log(snapshot)
      setSearchFilter(snapshot.docs.map((doc,idx) => {
        console.log(doc.data())
        return {
          ...doc.data(),
            name:doc.data().name
          }
      }))
      setSearchList(snapshot.docs.map((doc,idx) => {
        console.log(doc)
        return {
          ...doc.data(),
          name:doc.data().name
        }
      }))
    })
    return () => {
      unsubscribe()
    }
  },[])

它没有显示任何东西......就像它完全为空......但我可以看到pathsegments of singleRef......请问我如何获得这些文件?图是这样的

owner-items -> (single/group) -> image/s -> { document items }

【问题讨论】:

  • 如果我在下面回答中的建议有帮助,请告诉我。
  • 不,我不认为我不理解没有样品的哈哈哈哈..

标签: reactjs firebase google-cloud-firestore


【解决方案1】:

集合组由具有相同 ID 的所有集合组成,子集合位于特定文档下。要访问子集合,您需要在路径引用中指定该特定 ID。
使用Collection Group Queries 可能是从collectionGroup() 方法中传递的同名集合中获取所有文档的最简单方法。 您需要使用collection() 来获取CollectionReference 而不是返回DocumentReferencedoc()

还要检查Get Subcollectionfetching subcollection documents 的这些类似示例。

更新

如果您需要获取特定的嵌套子集合,您可以尝试类似于下面的内容

db.collectionGroup("orders").get().then((querySnapshot) => {
  console.log(querySnapshot.docs.map(d => ({id: d.id, ...d.data()})))
})

【讨论】:

    猜你喜欢
    • 2021-05-13
    • 1970-01-01
    • 1970-01-01
    • 2020-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多