【问题标题】:How to fetch documents in firestore with below data structure?如何使用以下数据结构在 Firestore 中获取文档?
【发布时间】:2023-03-08 00:33:01
【问题描述】:

我对在 Firestore 中获取的数据结构感到困惑。我只能满足#1 的要求。请帮帮我。

要求:

  1. 显示最新的 k 个帖子,不考虑任何用户(整个数据库中的最新 k 个帖子)

  2. 显示多个用户对应的帖子(我关注的用户对应的帖子)

以下是我能想到的两种数据结构,但仍然无法满足第二个要求。

数据结构1:

/posts/{postId}/
               -authorId          //one among /users/{userId}
               -message
               -date 
/users/{userId}/
               -name
               -etc...

Req1:显示最新的 k 个帖子,不考虑任何用户

constructor(private afs: AngularFirestore) {}

// code to fetch latest k posts
this.afs.collection("posts").ref
        .orderBy("date", "desc")
        .limit(k)
        .get().then(snapshot => {
              snapshot.forEach(postDoc => {
                   console.log(postDoc.data());
                   // rest of the code
              });
        });

Req2:显示多个用户对应的帖子 问题:在上面的代码中,如果我添加一个“where”方法,它只能过滤一个 authorId,而不是多个。 例如

this.afs.collection("posts").ref
        .where("authorId" == "xyz...")
        .orderBy("date", "desc")
        .limit(k)

数据结构2:

/users/{userId}/
               -name
               -etc...
               /posts/{postId}/      (collection inside user document)
                               -message
                               -date 

不确定,但我认为数据结构会比数据结构更有效,因为在查找与我关注的用户对应的帖子时,无需搜索整个帖子集合,而只需查看您关注的用户。 问题:如何获取上述数据结构中最新的k个帖子?

【问题讨论】:

    标签: angular firebase ionic-framework collections google-cloud-firestore


    【解决方案1】:

    您应该毫不犹豫地在您的数据库中维护这两种数据结构。这是 NoSQL 数据库中非常经典的方法,称为“非规范化”(与众所周知的 SQL DB 规范化相对)。

    看看这个article,它解释了 NoSQL 数据库的“数据建模技术”,并说“可以将非规范化定义为将相同的数据复制到多个文档或表中以简化/优化查询处理将用户的数据适合特定的数据模型”。

    缺点是您必须保持两个结构同步,但这可以通过 Firestore 中的 Batched Writes 轻松完成,请参阅此处的文档https://firebase.google.com/docs/firestore/manage-data/transactions#batched-writes

    【讨论】:

      猜你喜欢
      • 2023-02-25
      • 2018-04-10
      • 2023-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-26
      • 2021-01-12
      • 1970-01-01
      相关资源
      最近更新 更多