Firebase Javascript:以降序排列帖子

时间:2017-04-27 23:44:42

标签: javascript html firebase pagination

我的Firebase数据库存储了要向用户显示的帖子列表。我有一个分页,每个页面存储10个帖子。但是,在目前的形式中,数据库从最早的帖子到最新的帖子分页,而不是在这里显示最新的帖子。这是特别有问题的,因为Firebase不允许多个同时查询,我需要将密钥作为分页系统的一部分进行查询,因为每次用户进入下一页时我都需要存储页面的最后一个键,因为新页面上的所有帖子都将从上一页的最后一个键开始。如何确保帖子按降序(最新到最早)的顺序列出?

Firebase / Javascript

var database = firebase.database().ref();
var postsRef = database.child("posts");


var currentPage = 0;
var keyArray = [];
var limit = 0;

function listThoughts(page) {
    if (page == 0) {
        postsRef.orderByChild("key").limitToFirst(10).on("child_added", function(snapshot) {

            var thought = snapshot.val();

            $("#feed").append("<div class='thought2'><div class='heading'>Posted on " + thought.utctime + " by " + thought.username
            + " | <a href='#' class='reply'>Reply</a></div><div class='else'>" + thought.title + "</div></div");    

            keyArray[0] = thought.key;
        });
    }
    else {
        var elementCount = 0;

        console.log("Staring At: " + keyArray[page - 1]);

        postsRef.orderByChild("key").limitToFirst(10).startAt(keyArray[page - 1]).on("child_added", function(snapshot) {
            var thought = snapshot.val();
            console.log("THOUGHT: " + thought);
            $("#feed").append("<div class='thought2'><div class='heading'>Posted on " + thought.utctime + " by " + thought.username
            + " | <a href='#' class='reply'>Reply</a></div><div class='else'>" + thought.title + "</div></div");    

            keyArray[page] = thought.key;

            elementCount += 1;
        });

        if (elementCount < 10) {
            limit = page;
        }
    }
}

listThoughts(currentPage);

function changeTab(direction) {
    if (direction == -1 && currentPage > 0) {
        currentPage -= 1;
        console.log("Current Tab: " + currentPage);
        $("#feed").empty();
        listThoughts(currentPage);
    }
    if (direction == 1) {
        if (limit == 0 || currentPage < limit) {
            currentPage += 1;
            console.log("Current Tab: " + currentPage);
            $("#feed").empty();
            listThoughts(currentPage);
        }
    }
}

HTML

<div class="content-three">
    <div id="feed">
    </div>
</div>

<div class="center">
    <button onclick="changeTab(-1)">&lt;</button>
    <button onclick="changeTab(1)">&gt;</button>
</div>

这就是我的数据结构: Data Structure

1 个答案:

答案 0 :(得分:0)

我的解决方案是将日期存储为每个帖子的关键字。这样,我可以同时查询从最新到最旧的顺序中的所有帖子,同时能够跟踪页面的起始帖子。