【问题标题】:Firestore - Deep QueriesFirestore - 深度查询
【发布时间】:2018-01-03 20:42:07
【问题描述】:

我有一个 Firestore,其中包含一个包含子集合(称为“事物”)的集合(项目)。当我得到我的 Items 集合时,我得到了所有子文档,但没有得到任何子集合。我想做一个深度检索,一个名为 Items 的对象,其中包含子集合。

我知道这不可能开箱即用,但我正在努力自己编写代码来做到这一点。

谁能帮忙?

constructor(public afs: AngularFirestore) {
//this.items = this.afs.collection('Items').valueChanges();
this.itemsCollection = this.afs.collection('Items', ref => ref.orderBy('year', 'asc'));

this.items = this.itemsCollection.snapshotChanges().map(changes => {
  return changes.map(a => {
    const data = a.payload.doc.data() as Item;
    data.id = a.payload.doc.id;
    return data;
  });
});
}

getItems() {
 return this.items;
}

【问题讨论】:

    标签: javascript angular google-cloud-firestore


    【解决方案1】:

    是的,你可以执行下面的代码来得到你想要的。基本上,这段代码会为每个项目获取它的 things 子集合:

      getItems(): Promise<any> {
        return this.db.collection('items').get().then(
          items => {
            return this.getThingsForItems(items);
          });
      }
    
      getThingsForItems(items): Promise<any> {
        return Promise.all(items.docs.map(async (element) => {
          var things = []
          const response = await this.db.collection('items')
                                .doc(element.id).collection('things').get();
    
          response.forEach(subcollectionItem => {
            things.push(subcollectionItem.data());
          });
    
          return { Item: element.data(), Things: things }
        }));
      }
    

    getItems 方法将返回一个 Promise,其中包含您的项目及其 things 子集合。

    类似的东西:

    请记住,此查询可能会成为一个运行缓慢的查询,因为它正在获取项目集合的每个文档。 因此,您可能应该考虑对数据库进行非规范化或转换 items 文档数组中的 things 子集合(在这种情况下,您应该知道文档的最大大小为 1MB,因此如果您是数组,请不要考虑此选项可以成为太大了)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-09
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-14
      相关资源
      最近更新 更多