一起获取 Firestore collection 和 sub-collection 文档数据

Get Firestore collection and sub-collection document data together

我的 Ionic 5 应用程序中有以下 Firestore 数据库结构。

Book collection 有文档,每个文档有一个 Like sub-collection。 Like 的文档名称collection 是喜欢该书的用户ID。

我正在尝试查询以获取最新的 books,同时尝试从 Like sub-collection 获取文档以检查我是否喜欢它。

async getBook(coll) {
  snap = await this.afs.collection('Book').ref
    .orderBy('createdDate', "desc")
    .limit(10).get();

  snap.docs.map(x => {
    const data = x.data();
    coll.push({
      key: x.id,
      data: data.data(),
      like: this.getMyReaction(x.id)
    });
  }

async getMyReaction(key) {
    const res = await this.afs.doc('Book/myUserID').ref.get();
    if(res.exists) {
    return res.data();
  } else {
    return 'notFound';
  }
}

我在这里所做的是使用每本书 ID 调用方法 getMyReaction() 并将承诺存储在 like 字段中。后来,我在 HTML 中用 async 管道读取 like 值。这段代码运行良好,但是获取 like 值有一点延迟,因为 promise 需要时间来解决。有没有办法在我得到 collection 值的同时得到 sub-collection 值?

Is there a solution to get sub-collection value at the same time I am getting the collection value?

必须重组您的数据。 Firestore 查询只能考虑单个集合中的文档。唯一的例外是集合组查询,它允许您考虑所有集合中具有完全相同名称的文档。您现在正在做的“加入”这两个集合的工作可能与您将获得的效果差不多。

将其转换为单个查询的唯一方法是让另一个集合包含其他两个集合中的数据 pre-merged。这实际上在 nosql 数据库上很常见,被称为非规范化。但这完全取决于您来决定这是否适合您的用例。