You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firebase 9 如何访问指定postId的posts文档下的comments集合?

你编写的代码存在的核心问题是map方法的回调函数没有返回值,导致最终存储到comments状态的数组元素全是undefined。

修正要点

  • 箭头函数如果用花括号包裹执行逻辑,需要显式添加return语句返回数据;也可以直接去掉花括号使用隐式返回,简化写法。
  • 建议在返回的评论数据中补充文档id字段,方便后续对单条评论做更新、删除等操作。
  • 补充异步请求的异常捕获逻辑,避免请求报错影响页面正常运行。

修正后代码

const fetchComments = async() => {
  try {
    // 获取posts下指定id的文档引用
    const postRef = doc(db, 'posts', postId);
    // 获取comments子集合引用
    const commentsRef = collection(postRef, "comments");
    // 查询子集合数据
    const snapshot = await getDocs(commentsRef);
    // 遍历组装数据,补充文档id
    setComments(snapshot.docs.map((doc) => ({
      id: doc.id,
      ...doc.data()
    })));
  } catch (err) {
    console.error("获取评论失败:", err);
  }
}

如果运行后仍无法拿到数据,可以先确认postId变量的值和数据库中posts集合的对应文档id完全匹配,同时检查Firebase安全规则是否开放了comments集合的读权限。

内容的提问来源于stack exchange,提问作者CoderNewbie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 14:45:03