在 Firebase 中使用 limit、orderBy 和 startAfter 时,如何避免丢失数据?

问题描述

如果您订购的内容没有唯一值,您是否会错过数据?

例如,如果我有一个函数说:

export async function getCities(){

  const result = await firebase
  .firestore()
  .collection('cities')
  .orderBy('population','desc')
  .limit(5)
  .get();

  const CityResults = result.docs.map((city)=> ({
    ...city.data(),docId: city.id
  }));

如果我限制为 5 并且我的最后一条数据的人口为 1000,我的 getMoreCities() 函数会说

startAfter(1000)

但假设有 7 个城市的人口恰好为 1000,那么您会错过两个 firestore 调用的数据。

你不能startAfter(documentId)

解决方法吗?

解决方法

Firestore 将文档 ID 隐式添加到您指定锚文档的每个查询中,因此如果您传入 DocumentSnapshot,它已经可以工作了。

您还应该能够将文档 ID 作为最后一个参数传递给您的 startAfter 变体,尽管我必须承认我自己总是为此目的使用 DocumentSnapshot

下面是一个示例:

citiesRef.orderBy("population").startAt(860000).limit(1).get().then((snapshot) => {
  var lastdoc;
  snapshot.forEach(function(doc) {
    console.log("1: "+doc.id);
    lastdoc = doc;
  });
  citiesRef.orderBy("population").startAfter(lastdoc).limit(1).get().then((snapshot) => {
    snapshot.forEach(function(doc) {
      console.log("2: "+doc.id);
      lastdoc = doc;
    });
  });
});

工作版本:https://jsbin.com/sibimux/edit?js,console

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...