【问题标题】:How do I know if there are more documents left to get from a firestore collection?我如何知道是否还有更多文档需要从 Firestore 集合中获取?
【发布时间】:2022-11-30 03:06:43
【问题描述】:

我正在使用 flutter 和 firebase。我使用分页,每页最多 5 个文档。我怎么知道是否还有更多文档需要从 Firestore 集合中获取。我想使用此信息来启用/禁用呈现给用户的下一页按钮。

限制:5(每次5个文件)

orderBy:“日期”(最新的优先)

startAfterDocument: latestDocument(只是一个保存最新文档的变量)

这就是我获取文件的方式。

collection.limit(5).orderBy("date", descending: true).startAfterDocument(latestDocument).get()

我考虑过检查从 firestore 收到的文档数量是否等于 5,然后假设有更多文档要获取。但是如果我在集合中总共有 n * 5 个文档,这将不起作用。

我考虑过获取集合中的最后一个文档并存储它,并将其与我得到的批次中的每个文档进行比较,如果有匹配项,那么我知道我已经读完了,但这意味着阅读过多。

或者,也许我可以继续获取文档,直到我得到一个空列表并假设我已经到达集合的末尾。

我仍然觉得有更好的解决方案。

如果您需要更多信息,请告诉我,这是我关于此帐户的第一个问题。

【问题讨论】:

    标签: firebase flutter dart google-cloud-firestore pagination


    【解决方案1】:

    响应中没有标志表明还有更多文档。常见的解决方案是请求比您需要/显示的文档多一个文档,然后使用最后一个文档的存在作为存在更多文档的指示符。

    这也是数据库在其响应中包含此类标志所必须执行的操作,这可能就是为什么这不是 SDK 中的显式选项的原因。

    您可能还想查看 keeping a distributed count of the number of documents in a collection 上的文档,因为这是确定是否需要启用 UI 以加载下一页的另一种方法。

    【讨论】:

    • 我明白。非常感谢您的回答和解释。我会做的。
    • @userh309 我相信您必须使用解决方法来实现此目的的原因是,否则您将不得不查询总集合大小。在非常大的集合中,这将是一个巨大的性能损失
    【解决方案2】:

    这是一种从 firebase 集合中获取大量数据的方法

    let latestDoc = null; // this is to store the last doc from a query 
     //result
    const dataArr = []; // this is to store the data getting from firestore
    let loadMore = true;  // this is to check if there's more data or no
    
    const initialQuery = async () => {
      const first = db
       .collection("recipes-test")
       .orderBy("title")
       .startAfter(latestDoc || 0)
       .limit(10);
    
    const data = await first.get();
    
      data.docs.forEach((doc) => {
    
       // console.log("doc.data", doc.data());
    
        dataArr.push(doc.data()); // pushing the data into the array
      });
    
     //! update latest doc
     latestDoc = data.docs[data.docs.length - 1];
    
     //! unattach event listeners if no more docs
     if (data.empty) {
      loadMore = false;
      }
    
     };
    
      // running this through this function so we can actual await for the 
      //docs to get from firebase
     const run = async () => {
      // looping until we get all the docs
         while (loadMore) {
          console.log({ loadMore });
          await initialQuery();
        }
      };
    

    【讨论】:

      猜你喜欢
      • 2019-12-07
      • 2021-11-23
      • 1970-01-01
      • 2020-08-08
      • 2018-04-04
      • 1970-01-01
      • 2018-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多