如何使用Firebase对已过滤的结果进行分页?

时间:2020-04-28 09:36:22

标签: javascript firebase filter google-cloud-firestore pagination

我有一个保存在如下所示的firestore集合中的客户列表:

  • customer_1234

    • 名称:customer1
    • 类别:category1
    • city:city1
    • 国家:country1
  • customer_5678

    • 名称:customer2
    • 类别:category2
    • city:city2
    • 国家:country2
  • 其他客户...

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

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

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

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

谢谢! :)

1 个答案:

答案 0 :(得分:2)

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

例如,最后一个例子:

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");

});