Firebase实时数据库分页

3
我正在尝试为我的Express + Firebase实时数据库SDK添加一些分页功能,但我不确定如何实现,而且文档没有帮助我。此外,我找到的所有示例都涉及Firestore。
以一个模型User为例,可以通过database.ref('users')访问。假设我有10个用户,他们的ID分别从1到10,并且我想每页显示5个用户。
我期望的是获取键从1到5的用户,然后当有人点击第二页时,它将获取键从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的文档后按日期排序。


这个文档准确地描述了你想要的内容。 - Eldar
1
@Eldar,就像问题中所提到的那样,它展示了如何使用Firestore实现,我需要实时数据库的具体实现方法。 - Maramal
你找到解决方案了吗?我正在苦苦挣扎,哈哈。 - Cedric Hadjian
1个回答

2
我曾经遇到过一个很相似的情况,不过正好相反 - 我想显示最近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. ? - Artan M.
这可能是由于正在排序的数据,如果数据存储为字符串类型,即orderByChild是一个类似于“firstname”的参数,那么您必须将StartAt等值作为字符串传递。 - Miles Barette Duckworth

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接