I have a site where I want to add articles through Firebase, and I came up with the following code that displays the summary of articles, but it is some articles created by the user, and I want to modify it to display all articles created by other users
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")
})
}
This is some associated logic which justifies the structure
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")
});
}
It looks like you have a structure like this:
$userName: {
Posts: {
"post1": { ... },
"post2": { ... },
...
}
}
Right now you're loading the posts from a specific user, and adding them to the HTML. To load the posts of all users, you'll need to:
firebase.database().ref().on("value", function(users) {
var t = "";
users.forEach(function(user) {
user.val().Posts.forEach(function(post) {
... handle post here
})
})
})
You'll note that we no longer order on updatedAt, as that is not possible in your current data structure across all users. If you want to show all posts for all users by updatedAt, consider changing your data structure to a flat list of posts, with the user name being a property in each:
Posts: {
"post1": { username: "...", ... },
"post2": { username: "...", ... },
...
}