当存在子集合时,为什么从 Firestore 检索的数据返回空数组?

3 node.js firebase firebase-admin google-cloud-firestore

我正在尝试使用 angularfire2 从我的 firestore 数据库中检索数据。这就是我当前的数据库的样子。我有一个用户集合,其中包含将 userDetails 和 userPosts 绑定在一起的 userId 文档。 在此输入图像描述

但是,当我查询这个集合时,它在控制台中返回一个空数组。

在此输入图像描述

我正在使用 firebase 函数来检索数据。

Firebase 函数索引.ts

export const getFeed = functions.https.onCall(async (req,res) =>{
  const docs = await admin.firestore().collection('users').get()
    return docs.docs.map(doc => {
    return {
        postID: doc.id,
        ...doc.data()
         }
     }) 
 })
Run Code Online (Sandbox Code Playgroud)

TS文件

  tabTwoFeedInit (){    
      const getFeed = this.aff.httpsCallable('getFeed')
      this.ajax = getFeed({}).subscribe(data=> {
        console.log(data)
        this.posts =  data 
          })  
      }
Run Code Online (Sandbox Code Playgroud)

如何成功从此 Firebase 数据库检索数据?

rob*_*emb 5

Firestore读取是浅的,因此它们不会自动返回子集合。因此,您get()将仅返回文档 ID,因为该文档没有字段。

要返回文档的子集合,您需要调用该文档的getCollections 方法。这只能通过管理 API 来完成,但这对您来说应该没问题,因为您是在云函数中运行。正如文档所述,通常期望集合名称是可预测的(正如您的情况所示),但如果不是,您可能会考虑重组数据。

为什么浅读是可取的?它可以避免检索可能与用户相关的潜在大量信息集合,因此您可以更自然地构建数据。根据数据的大小,作为映射的字段可能更有意义userDetails(但集合可能更适合userPosts)。