如何使用 angularfire 进行查询以检索 firebase 中的集合和子集合?

How to make a query that retrieve a collection and a subcollection in firebase with angularfire?

我的 firebase 数据库中有以下结构:

/profiles/{uid}/displayName
               /email
               /otherAttribues
               /roles/{roleName}/someAttribute
                                /someOtherAttribute

所以“角色”是一个子集合,主要是因为它必须具有与配置文件的其余部分不同的写入权限。

在我的组件中,我目前正在检索配置文件:

  constructor(private firestore: AngularFirestore) {
    this.users$ = this.firestore.collection<User>('profiles').valueChanges();
  }

在我的 html 中,我在 *ngFor 循环中使用此 users$ 来在网格中显示配置文件。我需要添加一列,该列将根据 ID 为“admin”或“user”的角色的 presence/absence 显示。这可以从其他用户修改,因此它必须是可观察的。

如何检索我的配置文件的“角色”(至少是子集合中文档的 ID)并仍然很好地迭代它们?

这可以改变,所以我需要它是一个可观察的。我找不到在我的请求中“包含”子集合的方法。

根据角色,我需要

Firestore 读取很浅,它们只从您命名的集合(组)中读取,因此在您的情况下是从 user 中读取。无法在同一操作中同时读取子集合。

有关用户角色的信息有两个常用选项:

  1. 为每个单独的用户执行额外的读取操作,或者通过 collection group query 一次对所有 roles 个集合执行。
  2. 通过将 roles 中的相关信息复制到 user 中的父文档中。

鉴于您的查询要求非常简单,我可能会选择(也)将信息存储在 user 文档中,直接来自客户端,或者通过每当roles 数据已更新。

我在我的用户组件中完成了以下操作:

this.users$ = this.firestore.collection<User>('profiles').valueChanges({ idField: 'uid' }).pipe(
      switchMap((profiles) => {
        const res = profiles.map(profile => {
          return this.firestore.collection(`profiles/${profile.uid}/roles`).valueChanges({ idField: 'Id' }).pipe(
            map(doc => {
              return doc.map(d => d.Id)
            }),
            tap(roles => {
              //TODO: consolidate the profile with the roles here
              //This will be updated on changes
            }),
            map(roles => Object.assign(profile, { roles }))
          );
        })
        return combineLatest(...res);
      })
    );

注意:它警告我有关 combineLatest 的弃用,但不确定如何替换它。