首页 > 解决方案 > 如何使用 Firebase 对过滤后的结果进行分页?

问题描述

我有一个保存在这样构建的 firestore 集合中的客户列表:

现在,我想创建一个带有一些过滤器的客户存档页面(按名称、按类别、按城市、按国家/地区)。

我想使用无限滚动系统一次显示 20 个结果。

例如,我可以请求某个城市的所有客户,然后我可以添加第二个过滤器(按类别)并将它们混合在一起。

构建这个系统的最佳方法是什么?

谢谢!:)

标签: javascriptfirebasefiltergoogle-cloud-firestorepagination

解决方案


您只需使用文档中描述的技术对查询进行分页。

例如,在您的最后一个示例中:

var first = db.collection("customers")
        .where('city', '==', 'city1')
        .where('category', '==', 'category1')
        .limit("20");

return first.get().then(function (documentSnapshots) {
  // Get the last visible document
  var lastVisible = documentSnapshots.docs[documentSnapshots.docs.length-1];
  console.log("last", lastVisible);

  // Construct a new query starting at this document,
  // get the next 20 customers.
  var next = db.collection("customers")
        .where('city', '==', 'city1')
        .where('category', '==', 'category1')
        .startAfter(lastVisible)
        .limit("20");

});

推荐阅读