【问题标题】:Why is data retrieved from Firestore returning empty array when there are subcollections present?当存在子集合时,为什么从 Firestore 检索的数据返回空数组?
【发布时间】:2020-02-27 22:26:02
【问题描述】:

我正在尝试使用 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()
         }
     }) 
 })

TS 文件

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

我怎样才能成功地从这个 firebase 数据库中检索数据?

【问题讨论】:

    标签: node.js firebase google-cloud-firestore firebase-admin


    【解决方案1】:

    Firestore reads are shallow,因此它们不会自动返回子集合。因此,您的 get() 将只返回文档 ID,因为该文档没有字段。

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

    为什么需要浅读?它可以避免检索可能与用户相关联的大量信息,因此您可以structure data more naturally。根据数据的大小,作为映射的字段可能对userDetails 更有意义(但对于userPosts,集合可能是正确的)。

    【讨论】:

      【解决方案2】:

      如果您只是创建云函数来从该结构中检索帖子。我更愿意稍微重构数据库,只在客户端使用集合组查询(不需要云功能)来拉帖子。

      我的意思是重组,你应该将userID存储在userPosts子集合的文档中。

      然后只需用户Collection Group Query 即可检索特定用户的帖子。

      语法是firebase javascript库。你可以发现它相当于 angularfire

      let posts= db.collectionGroup('userPosts').where('userId', '==', 'some-user-id');
      

      【讨论】:

        猜你喜欢
        • 2022-12-22
        • 2021-07-03
        • 1970-01-01
        • 1970-01-01
        • 2020-01-25
        • 2021-06-02
        • 2019-08-16
        • 2021-03-10
        • 2020-02-27
        相关资源
        最近更新 更多