Firebase JavaScript网页应用改造:实现查看所有会员发布的文章功能
问题核心
你当前的Firebase Realtime Database数据结构是将每个用户的文章存储在/{用户displayName}/Posts/独立路径下,原代码仅查询当前登录用户对应的路径,因此只能展示自己的文章。
修改后的全量文章展示代码
function allIndex(){ firebase.auth().onAuthStateChanged(function(currentUser) { if (currentUser) { // 直接查询数据库根节点,遍历所有用户的节点 firebase.database().ref().orderByKey().on("value", function(rootSnapshot) { let allPostHtml = ""; // 遍历每个用户节点 rootSnapshot.forEach(function(userNode) { // 只处理用户节点下的Posts子节点,跳过其他根节点数据 const postsRef = userNode.child("Posts"); if (postsRef.exists()) { // 遍历当前用户的所有文章 postsRef.forEach(function(postSnapshot) { const entry = postSnapshot.val(); // 链接追加作者参数,避免详情页找不到对应文章 const postUrl = `my-posts.html?author=${encodeURIComponent(userNode.key)}&id=${postSnapshot.key}`; allPostHtml = `<div class="article"><a href="${postUrl}"><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>` + allPostHtml; }) } }); $("#entries.post").removeClass("loading").find(".loader").remove(); $("#entries.post .panel_content").append(allPostHtml); }) } else { alert("Please login first"); window.location.href = "sign-in.html"; } }) }
配套调整说明
- 安全规则配置:需要在Firebase控制台的数据库安全规则中开放所有用户Posts路径的读权限,示例规则如下:
{ "rules": { "$username": { "Posts": { ".read": "auth != null", ".write": "auth != null && auth.token.name === $username" }, "Points": { ".read": "auth != null && auth.token.name === $username", ".write": "auth != null && auth.token.name === $username" } } } }
- 详情页适配:
my-posts.html需要新增获取author参数的逻辑,查询路径改为firebase.database().ref(作者名).child("Posts").child(文章ID)才能正常加载文章内容。
性能优化建议
如果后续用户量、文章量较大,遍历所有用户节点的查询方式性能会下降,建议调整数据存储结构,新增全局AllPosts根节点,发布文章时同时写入用户私有路径和全局路径,每篇文章补充author字段存储作者displayName,后续查询全量文章直接访问/AllPosts路径即可,不需要遍历用户节点。
采用该方案时,需要对原create函数新增全局写入逻辑:
a.push(e).then(function(ref) { // 新增写入全局文章节点逻辑 firebase.database().ref('AllPosts').child(ref.key).set({ ...e, author: n.displayName }).then(() => { window.location.href = "my-posts.html?id=" + ref.getKey() }) })
内容的提问来源于stack exchange,提问作者Mohammad QT
相关产品推荐
相关产品推荐

