Firestore 分页 - 上一页

Dav*_*ave 7 javascript firebase google-cloud-firestore

我是 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];
    });
Run Code Online (Sandbox Code Playgroud)

下一个按钮

$("#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];
        });
    });
Run Code Online (Sandbox Code Playgroud)

上一页(代码问题)

    $("#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);
            });
        });
    });
Run Code Online (Sandbox Code Playgroud)

我在 startAt 处使用变量firstVisible,并在单击“下一步”按钮时设置其值,但单击它无法按预期工作。

老实说,我不确定需要在firstVisible变量上设置什么才能获取上一个文档快照

任何帮助将不胜感激

小智 12

$("#js-previous").on('click', function () {
    $('#employee-table tbody').html('');
    var previous = db.collection("employees")
        .endBefore(firstVisible)
        .limitToLast(3);
    previous.get().then(function (documentSnapshots) {
        documentSnapshots.docs.forEach(doc => {
            renderEmployee(doc);
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

尝试将 endBefore 与 limitToLast 一起使用。limitToLast 将返回第一个可见文档之前的最后一个文档。希望这有帮助!