You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firestore .endBefore返回错误数据,分页功能异常求助

Firestore分页中endBefore失效的问题解决

问题根源

当使用endBefore进行向前分页时,你的查询保持正序排列,此时endBefore(doc)会返回所有在目标文档之前的结果,再用limit(10)取前10条——这自然就是整个集合的前10条数据,而非目标文档之前的最后10条,导致回退分页失效。

修复方案

向前分页时需要先倒序查询,获取目标文档之前的最后limit条数据,再将结果反转回正序。同时要调整分页标记(beforeRate/afterRate)的计算逻辑,因为倒序后的文档顺序和最终展示顺序相反。

修改后的代码:

async function newReturnAllRates(limit = 15, before = null, after = null) {
  let rates = [];
  let beforeRate = null;
  let afterRate = null;
  let doc = null;

  const ratesCollectionRef = db.collection("rates");

  if (before || after) {
    doc = await ratesCollectionRef
      .doc(before || after)
      .get()
      .then((doc) => {
        if (!doc.exists) {
          console.log("目标文档不存在");
          return;
        }
        return doc;
      })
      .catch(function (error) {
        console.log("获取参考文档失败: ", error);
      });
  }

  let query = ratesCollectionRef
    .orderBy("name")
    .orderBy("type")
    .orderBy("subsidiary")
    .orderBy("rate");

  let isReverse = false;
  if (doc && doc.id) {
    if (before) {
      // 向前分页:倒序查询,获取目标文档之前的最后limit条
      query = query.endBefore(doc)
        .orderBy("name", "desc")
        .orderBy("type", "desc")
        .orderBy("subsidiary", "desc")
        .orderBy("rate", "desc");
      isReverse = true;
    } else {
      // 向后分页:保持正序
      query = query.startAfter(doc);
    }
  }

  await query
    .limit(limit)
    .get()
    .then((snapshot) => {
      if (snapshot.empty) {
        console.log("数据库中没有数据");
        return;
      }

      // 倒序查询的结果需要反转回正序,保证展示顺序正确
      const docs = isReverse ? snapshot.docs.reverse() : snapshot.docs;
      docs.forEach((doc) => {
        rates.push({ ...doc.data(), id: doc.id });
      });

      // 适配倒序场景的分页标记计算
      if (isReverse) {
        beforeRate = snapshot.size < limit ? null : snapshot.docs[limit - 1].id;
        afterRate = snapshot.docs[0].id;
      } else {
        beforeRate = snapshot.docs[0].id;
        afterRate = snapshot.size < limit ? null : snapshot.docs[limit - 1].id;
      }
    })
    .catch(function (error) {
      console.log("获取数据失败: ", error);
    });

  return { rates, beforeRate, afterRate }; // 原代码中ratesCount未定义,请自行补充对应逻辑
}

关键调整说明

  • 向前分页时,将所有orderBy的排序方向改为desc,配合endBefore精准获取目标文档之前的最后limit条数据
  • 获取快照后用reverse()将结果转回正序,保证前端展示顺序符合预期
  • 分页标记beforeRate和afterRate的计算逻辑适配倒序场景:倒序快照的首尾对应正序结果的尾首,需反向赋值

内容的提问来源于stack exchange,提问作者NaguiHW

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 01:28:33