首页 > 解决方案 > 在 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 人,那么您会错过两个消防站呼叫的数据。

看起来很傻,你不能startAfter(documentId)

有解决方法吗?

标签: javascriptfirebasegoogle-cloud-firestore

解决方案


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

您还应该能够将文档 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


推荐阅读