我是Firebase的新手,正在尝试分页查询。我喜欢有一个“下一个”和“上一个”按钮。我的下一个按钮运行正常,我的问题是单击上一个时
参考:https://firebase.google.com/docs/firestore/query-data/query-cursors
目前,我的收藏夹中有10个文档,我希望一次显示3个。
加载时我仅显示3个项目
var first = db.collection("employees").limit(3);
first.get().then(function (documentSnapshots) {
documentSnapshots.docs.forEach(doc => {
//function to display in the HTML
renderEmployee(doc);
});
lastVisible = documentSnapshots.docs[documentSnapshots.docs.length - 1];
});
下一个按钮
$("#js-next").on('click', function () {
$('#employee-table tbody').html('');
var next = db.collection("employees")
.startAfter(lastVisible)
.limit(3);
next.get().then(function (documentSnapshots) {
documentSnapshots.docs.forEach(doc => {
//function to display in the HTML
renderEmployee(doc);
});
lastVisible = documentSnapshots.docs[documentSnapshots.docs.length - 1];
firstVisible = documentSnapshots.docs[documentSnapshots.docs.length - 1];
});
});
上一页(代码问题)
$("#js-previous").on('click', function () {
$('#employee-table tbody').html('');
var previous = db.collection("employees")
.startAt(firstVisible)
.limit(3);
previous.get().then(function (documentSnapshots) {
documentSnapshots.docs.forEach(doc => {
renderEmployee(doc);
});
});
});
我在startAt使用变量firstVisible,并且在单击下一个按钮时设置了它的值,但是单击它无法按预期方式工作。
老实说,我不确定我需要在firstVisible变量上设置什么才能获取先前的文档快照
任何帮助将不胜感激
最佳答案
Firestore分页基于了解锚文件:涉及两个页面的锚文件。
通常,这将是当前页面的最后一个文档,也是下一页的第一个文档。或者实际上,如果您使用startAfter()
,它将是下一页之前的文档。
但是,由于要向后分页,因此锚文档是当前页面上的第一个文档,也是前一页上的最后一个文档。这意味着您需要:
反转查询的排序顺序。
从锚文档开始(或之后)。
所以像这样:
var previous = db.collection("employees")
.orderBy(firebase.firestore.FieldPath.documentId(), "desc")
.startAt(firstVisible)
.limit(3);