【问题标题】:Querying Subcollection into Document with Firebase使用 Firebase 将子集合查询到文档中
【发布时间】:2020-03-10 11:08:14
【问题描述】:

我设置了一个 Angular 8 打字稿界面,其中包括另一个界面的数组作为变量。如下所示:

export interface User {
    name: string;
    id: string;
    history: Job[];  //this is what is not getting generated
}

Job 界面如下所示:

export interface JobJson {
    id: string;
    price: number,
    notes: string
}

我使用 Firebase 的 Cloud Firestore 作为我的数据库,数据库结构如下所示:

用户 // 集合

|--> user1234 // 文档

|--> 作业 //子集合

|--> job1234 // 子文档

当我从 firebase 查询用户时:

this.firestore.collection<UserJson>('users').doc<UserJson>(id).valueChanges().subscribe((u) => {
    // do whatever with u
  });

正如预期的那样,它没有填写历史记录:Jobs[]。但是,在我的程序中,我需要将 user.history 数组设置为 firebase 中 user 下的子集合。这怎么可能完成?感谢您的帮助!

【问题讨论】:

  • 您想获得正确的子集合作业吗?
  • @JoséSoní 是的,文档的子集合。我创建了一个只有两个调用的解决方法,一个用于文档用户,另一个用于 JobJson

标签: angular typescript firebase google-cloud-firestore


【解决方案1】:

据我所知,仅通过一次调用 firestore 就无法做到这一点。如果您知道哪个集合,则最接近的是两个调用解决方法,如果您不知道集合名称,则最接近的是三个。

here 也是文档,没有任何方法用于 documentReference 获取文档快照和集合。

在我的情况下,我将添加两种解决方法,代码只是在控制台中打印内容。

不知道子集合名称:它获取所有子集合及其元素:

db.collection('users').doc(str[6]).get().then(documentSnapshot => {
  console.log(documentSnapshot.data());
});

db.collection(COLLECTION_ID).doc(DOCUMENT_ID).listCollections().then(collections => {
  for (let collection of collections) {
    console.log(`Found subcollection with id: ${collection.id}`);
    collection.get().then((snapshot) => {
      snapshot.forEach((doc) => {
        console.log(doc.id, '=>', doc.data());
      });
    })
    .catch((err) => {
      console.log('Error getting documents', err);
    });
  }
});

了解您想要获取的子集合:

db.collection(COLLECTION_ID).doc(DOCUMENT_ID).get().then(documentSnapshot => {
  console.log(documentSnapshot.data());
});

db.collection(COLLECTION_ID).doc(DOCUMENT_ID).collection(SUBCOLLECTION_ID).get()
  .then((snapshot) => {
    snapshot.forEach((doc) => {
      console.log(doc.id, '=>', doc.data());
      console.log(doc.id, '=>', JSON.stringify(doc));
    });
  })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-20
    • 2021-09-05
    • 2020-07-26
    • 2018-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多