【问题标题】:Firebase Real time database paginationFirebase 实时数据库分页
【发布时间】:2020-07-07 06:57:14
【问题描述】:

我正在尝试向我的 Express + Firebase 实时数据库 SDK 添加一些分页功能,但我不确定如何实现这一点,documentation 对我没有帮助。此外,我发现的所有示例都与 Firestore 有关。

作为一个例子,我有这个模型 Userdatabase.ref('users') 访问。想象一下,我有 10 个用户,他们的 ID 分别从 1 变为 10,我想每页分页 5 个。

我的期望是得到键从 1 到 5 的用户,然后当有人点击第 2 页时,它会得到键从 6 到 10 的用户。

根据文档,我知道我应该添加如下内容:

(req, res) => {
    const { key } = req.query;
    let ref = database.ref('users')
                  .orderByChild('createdAt')
                  .limitToLast(5);
    if (key) { 
        ref = ref.startAt(key);
    }

    ref.once('value')
        .then(snapshot => ...);
}

到目前为止,我得到的是limitToLast()limitToFirst() 之间的区别在于排序,分别类似于ORDER BY createdAt DESCORDER BY createdAt ASC

如果我设置ref.startAt(5),则前面的代码不起作用,因为我得到了前五个用户(1 到 5)。

我应该使用什么方法?提前致谢。

编辑:

我知道如果我这样做 database.ref('users').orderByChild('createdAt').limitToLast(5).startAt(5) 我会得到 createdAt 大于 5 的文档,这是错误的。我应该在得到那些键在 5 旁边的文档后按日期排序。

【问题讨论】:

  • 这个document 准确地描述了你想要什么。
  • @Eldar,如问题中所述,它展示了如何使用 Firestore 做到这一点,我需要实时数据库。
  • 您找到解决方案了吗?我在努力大声笑

标签: javascript node.js firebase express firebase-realtime-database


【解决方案1】:

我在一个非常相似的情况下苦苦挣扎,虽然相反 - 我想显示最后 10 条记录,然后分页到列表的开头(在我的情况下,列表是按日期排序的,我想显示最新日期优先);

但是,对于您的示例,我可以通过执行以下操作从 1-5 到 6-10 进行分页:

前 5 名用户:

database
  .ref('users')
  .orderByChild('createdAt')
  .limitToFirst(6) //Note here that the request is for the first 6 results
  .once("value")
  .then((snap) => {
    const firstSix = snap.val();
    const sixth = firstSix[5].createdAt; //assuming your data is an array, get the last entry


    const startAtNext =  sixth, //this is the 6th value used for pulling the next 5 results - this should be stored globally
    const currentUserList = firstSix.slice(0, firstSix.length -1), //the list of users 1-5
});

接下来的 5 位用户:

database
  .ref('users')
  .orderByChild('createdAt')
  .startAt(startAtNext) // Globally stored variable from first call
  .limitToFirst(6) //Note here that the request is for the first 6 results
  .once("value")
  .then((snap) => {
    const nextSix = snap.val();
    const sixth = nextSix[5].createdAt; //assuming your data is an array, get the last entry


    const startAtNext =  sixth, // the start index for the next request
    const currentUserList = firstSix.slice(0, firstJobsList.length -1), //the next 5 users
});

【讨论】:

  • 知道为什么我在尝试时总是得到这个Error: Query: When ordering by key, the argument passed to start At(), start After(), endAt(), end Before(), or equal To() must be a string. 吗?
猜你喜欢
  • 2021-10-12
  • 2022-10-14
  • 2019-02-12
  • 1970-01-01
  • 2020-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多