首页 > 解决方案 > 仅从一个已知子集合中检索所有文档

问题描述

我有这个 Firestore 结构:

Category: {
    document1a: {
        name : "reptiles"
        animalsubcollection: {
            Document1b: {
                name: "snake"
                color: "white"
            }
            Document2b: {
                name: "lizard"
                color: "black"
            }
    document2a: {
        name : "mammals"
        animalsubcollection: {
            Document1b: {
                name: "monkey"
                color: "brown"
            }
            Document2b: {
                name: "cat"
                color: "white"
            }

我需要在一个页面中列出该信息,按如下类别分类:

爬行动物:

哺乳动物:

像上面的例子一样,我总是只有一个已知的子集合,称为animalsubcollection.

我如何在 Angular 5 中使用 AngularFire2 来实现这一点?

如果它不是此类信息的最佳 Firestore 模型,我可以在必要时更改它。我接受其他人的建议以达到相同的结果。

标签: angularfirebaseionic3google-cloud-firestoreangularfire2

解决方案


感谢大家的建议,但最初的建议不是对原始数据库模型进行规范化,而是使用原始模型找到一个简单的解决方案。

我知道有时候,只需简单地创建 2 或 3 个新的规范化集合并解决问题就更容易了。另一方面,如果有可能创建子集合,则需要存在一种以 Angular em RxJS 方式查询其数据的方法。

因此,经过 2 或 3 天的研究,我找到了一种方法:

//necessary imports
import { Observable } from 'rxjs/observable';
import { combineLatest } from 'rxjs/observable/combineLatest';
import 'rxjs/add/operator/mergeMap';

// the observable for animals category collection
this.animals = this.afs
  .collection('Category')
  .snapshotChanges()
  .map(arr => {
    return arr.map(snap => {
      const categ = { id: snap.payload.doc.id, ...snap.payload.doc.data() };

      // the animalsubcollection, using the previous value as parameter
      return this.afs
        .collection(`Category/${categ.id}/animalsubcollection`)
        .valueChanges()
        .map(animalsub => {
          return { ...categ, animalSubs: animalsub };
        });
    });
  })
  .mergeMap(result => combineLatest(result));
  //thats the trick. Combine 2 observables into a new one.

在视图中:

<ion-card *ngFor="let animal of animals | async">
<p *ngFor="let as of animal.animalSubs">
     {{as.name}} - {{as.color}}
</p>

我希望它可以帮助某人


推荐阅读