首页 > 解决方案 > 查看 Firebase 上的所有成员文章!Javascript 网页应用

问题描述

我有一个网站,我想通过 Firebase 添加文章,我想出了以下显示文章摘要的代码,但它是用户创建的一些文章,我想修改它以显示由创建的所有文章其他用户

function allIndex(){
    firebase.auth().onAuthStateChanged(function(user) {
        user ? firebase.database().ref(user.displayName).child("Posts").orderByChild("updatedAt").on("value", function(user) {
            var t = "";
            user.forEach(function(user) {
                entry = user.val(), t = '<div class="article"><a href="my-posts.html?id=' + user.getKey() + '"><div class="panel-heading">' + excerpt(entry.title, 140) + '</div><div class="panel-body"><small>' + datetimeFormat(entry.updatedAt) + '</small></div></a><small class="' + entry.status + '">' + entry.status + "</small></div>" + t
            }), $("#entries.post").removeClass("loading").find(".loader").remove(), $("#entries.post .panel_content").append(t)
        }) : (alert("Please login first"), window.location.href = "sign-in.html")
    })
}

这是一些相关的逻辑,可以证明结构的合理性

function create() {
    firebase.auth().onAuthStateChanged(function(n) {
        n ? (tinymce.init({
          
        }), $("#new_entry").submit(function(e) {
            e.preventDefault(), (e = {}).title = $(this).find('[name="title"]').val(), e.description = $(this).find('[name="description"]').val(), e.labels = $(this).find('[name="labels"]').val(), e.content = tinymce.get("content").getContent(), e.createdAt = (new Date).getTime(), e.updatedAt = e.createdAt, e.views = 0, e.status = "Pending";
               var t = firebase.database().ref(n.displayName),
                a = t.child("Posts");
            return t.child("Points").transaction(function(e) {
                return (e || 0) + 10
            }), a.push(e).then(function(e) {
                window.location.href = "my-posts.html?id=" + e.getKey()
            }).catch(function(e) {
                alert(e), console.error(e)
            }), !1
        })) : (alert("Please login first"), window.location.href = "sign-in.html")
    });
}

标签: javascriptfirebasefirebase-realtime-database

解决方案


看起来你有这样的结构:

$userName: {
  Posts: {
    "post1": { ... },
    "post2": { ... },
    ...
  }
}

现在您正在加载来自特定用户的帖子,并将它们添加到 HTML。要加载所有用户的帖子,您需要:

  1. 从数据库中更高的一级加载数据。
  2. 然后在您的回调中遍历每个用户。
firebase.database().ref().on("value", function(users) {
  var t = "";
  users.forEach(function(user) {
    user.val().Posts.forEach(function(post) {
      ... handle post here
    })
  })
}) 

您会注意到我们不再订购updatedAt,因为在您当前的所有用户数据结构中这是不可能的。如果您想通过 显示所有用户的所有帖子updatedAt,请考虑将您的数据结构更改为帖子的平面列表,其中用户名是每个帖子的属性:

Posts: {
  "post1": { username: "...", ... },
  "post2": { username: "...", ... },
  ...
}

推荐阅读