首页 > 解决方案 > 使用 Cloud Firestore 的 Ionic App - 查看所有用户的数据

问题描述

我的数据结构如下:

collection(people)
   document (UserId1)
      collection(profiles)
         document (generatedId1)
            name: 'Speech1'
            type: 'admin'
   document (UserId2)
      collection(profiles)
         document (generatedId2)
            name: 'Client1'
            type: 'client'
      collection(tasks)
         document (generatedId3)
            date: '2018-12-30'
            time: 'AM'
            severity: 0
         document (generatedId4)
            date: '2018-12-30'
            time: 'PM'
            severity: 0
   document (UserId3)
      collection(profiles)
         document (generatedId5)
            name: 'Client2'
            type: 'client'
      collection(tasks)
         document (generatedId5)
            date: '2018-12-30'
            time: 'AM'
            severity: 0
         document (generatedId6)
            date: '2018-12-30'
            time: 'PM'
            severity: 0

这种结构允许我使用如下语句查询登录用户的任务集:

getTasks(){
    return new Promise<any>((resolve, reject) => {
      let currentUser = firebase.auth().currentUser;
      this.snapshotChangesSubscription = this.afs.collection('people').doc(currentUser.uid).collection('tasks').snapshotChanges()
      .subscribe(snapshots => {
        resolve(snapshots);
      })
    });
  }

但是,当我以管理员类型用户身份登录时,我希望查看所有用户的数据,因此我尝试构建和查询本质上将考虑人员集合中的所有文档的查询。

我怎样才能做到这一点?

标签: javascriptfirebaseionic3google-cloud-firestore

解决方案


但是,当我以管理员类型用户身份登录时,我希望查看所有用户的数据,因此我尝试构建和查询本质上将考虑人员集合中的所有文档的查询。

我怎样才能做到这一点?

不幸的是,您不能使用此数据库模式。Firestore 中的查询很浅,这意味着它们只能从运行查询的集合中获取项目。无法在单个查询中从顶级集合和其他集合或子集合中获取文档。Firestore 不支持一次性跨不同集合进行查询。单个查询只能使用单个集合中文档的属性。所以我能想到的最简单的解决方案是添加另一个集合,您应该在其中添加所有存在于 all 中的所有子集合中的所有“文档” people collection -> uid -> generatedId。因此,您的架构可能与此类似:

Firestore-root
   |
   --- allDocuments (collection)
         |
         --- generatedId1 (document) //The unique id of the document
         |     |
         |     --- name: 'Speech1'
         |     |
         |     --- type: 'admin'
         |     |
         |     --- uid: 'UserId1'
         |
         --- generatedId 2(document) //The unique id of the document
               |
               --- name: 'Client1'
               |
               --- type: 'client'
               |
               --- uid: 'UserId2'

为了显示所有这些用户,只需在allDocuments引用上附加一个侦听器并获取所有users对象。如果您想获取所有管理员用户,只需使用Query如下所示的:

var allDocumentsRef = db.collection("allDocuments");
var query = allDocumentsRef.where("type", "==", "admin");

推荐阅读