Firebase实时数据库分页



我正试图在Express+Firebase实时数据库SDK中添加一些分页功能,但我不确定如何实现,文档对我没有帮助。此外,我找到的所有示例都是关于Firestore的。

作为一个例子,我有一个由database.ref('users')访问的User模型。想象一下,我有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旁边的文件后按日期排序。

我遇到了一个非常相似的场景,尽管反过来——我想显示最后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
});

最新更新