查询中的数据关系

时间:2019-12-13 00:13:54

标签: typescript firebase google-cloud-firestore angularfire2

我正在尝试在Firestore上运行查询,以获取特定城市的所有产品。我有一个stores集合,该集合具有一个名为city的属性和一个名为products的子集合。

我的想法是先查询它,然后访问每个项目的子集合,但是这样做很难。

这是我到目前为止所拥有的:

getProducts() {
   this.db.collection('stores', ref => ref.where('city', '===', 'New York').limit(10))
      .snapshotChanges().pipe(
         map(snaps => {
            snaps.map(snap => {
               const id = { id: snap.payload.doc.id };
               this.db.collection(`stores/${id.id}/products/`).snapshotChanges().pipe(
                  map({
                     productSnaps => {
                        productSnaps.map(productSnap => {
                            return productSnap.payload.doc.data() as Product;
                        })
                     }
                  })
               )
            })
         })
      )
}

有了这个,我得到了10个Observable的数组,所以我真的不能对数据做任何事情。

这是控制台日志:

  

[可观察,可观察,可观察,可观察,可观察,可观察,可观察,可观察,可观察,可观察](10)

谢谢!

1 个答案:

答案 0 :(得分:0)

我尝试复制您的数据模型:

enter image description here

enter image description here

这是我的解决方案(我正在使用Node.js),以获取属于City = New York的商店集合中属于某个文档的所有产品:

let collRef = db.collection('stores').where('city', '==',
  'New York').limit(2);

let query1 = collRef.get()
  .then(snapshot => {
    if (snapshot.empty) {
      console.log('No matching documents.');
      return;
    }

    snapshot.forEach(doc => {
        db.collection('stores').doc(doc.id).collection('products').get().then(
            snapshot => {snapshot.forEach(doc => {
                console.log(doc.id, '=>', doc.data());
            }
        )});

    });
  })
  .catch(err => {
    console.log('Error getting documents', err);
  });

和结果:

enter image description here