【问题标题】:Getting nested subcollections from a document从文档中获取嵌套子集合
【发布时间】:2018-11-30 05:27:40
【问题描述】:

所以我有一个如下所示的数据结构。用户有几个月的集合,月份有类别的集合,类别有交易的集合。我很难从查询中获取所需的数据。我可以得到如下所示的月份,但我很难弄清楚如何从月份文档中获取所有类别文档。

user
    email
    name
    --months collection
          month - name, amount
          --categories collection
                category - name, amount <-- I need all of these docs
                --transactions
                    transaction - amount, date

这是我可以获得月份的地方,但现在我需要该月份的所有类别,以便我可以在 html 中循环浏览它们。我想我需要当月的 id,所以我可以提取那个特定的,但据我所知,Observable 没有 id。有没有一种简单的方法可以做到这一点,还是我需要重新考虑我的数据结构?

  monthCollection: AngularFirestoreCollection<Month>;

  monthName: string;
  totalSpent: number;

  categories: Observable<Category[]>;

  constructor(public navCtrl: NavController,
              public navParams: NavParams,
              public alertCtrl: AlertController,
              private firestoreProvider: FirestoreProvider) {

    // Just need the data from the first month
    this.firestoreProvider.getMonthObservable().forEach(doc => {
      this.monthName = doc[0].name.substring(0, 3);
      this.totalSpent = doc[0].totalSpent;
    });
  }

【问题讨论】:

    标签: javascript angular typescript firebase ionic-framework


    【解决方案1】:

    除非您有充分的理由不这样做,否则 Firestore 会提供更好的(复合)查询功能。如果您必须使用实时数据库,则需要按照他们的文档Structure Your Database 中的说明来扁平化您的数据库架构。

    数据结构的最佳实践

    • 避免嵌套数据
    • 扁平化数据结构

    【讨论】:

    • 我不认为 OP 正在使用实时数据库 - 他似乎已经在使用 Cloud Firestore(目前仍处于测试阶段)。他们似乎还需要特定月份以下的类别 - 复合查询会对此有所帮助吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-13
    • 2021-08-20
    • 2013-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多