Firebase 获取三级数据

Firebase fetch 3rd level data

我正在尝试查询第三级的 firebase 数据。

我正在使用以下代码。

from(this.firestoreDb
        .collection('userPosts')
        .doc('123')
        .collection('posts', ref => ref.where('id', '==', 999))
        .snapshotChanges())
        .subscribe(res => {
            console.log(res);
        });

我正在尝试查询内容,但上面的代码 returns 为空数组。 我可以仅使用 .doc(123) 获取所有 post,但不能获取特定的 post。 我还需要帮助来更新每个 post 的评论。请帮忙。

.where("id", "==", 999) 将尝试在 userPosts 集合中查找字段 id 等于 999 的文档,而不是通过数组进行搜索。您无法使用数组中的任何字段进行查询(除非您知道整个对象的原样)。如果您需要此类查询,则必须将其转换为地图或使用子集合。

您可以直接将 post 存储在您的 userPosts 集合中,其中的每个文档都是一个 post。只需确保您在该文档中有用户 ID 和 postID。该文档可能类似于:

{
  userID: "user_id",
  postID: "post_id",
  ...otherDocFields
}

现在您可以轻松查询由用户或具有给定 ID 的 post 创建的 post:

from(this.firestoreDb
        .collection('userPosts', ref => ref.where('postID', '==', 999))
        .snapshotChanges())
        .subscribe(res => {
            console.log(res);
        });