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

Firestore评论添加异常:跨用户评论未存入指定子集合

问题分析与解决方案

问题根源

当前代码构建Firestore路径时,使用的authorId是评论者的UID,而非目标帖子的发帖人UID。这导致评论他人帖子时,路径变为posts/评论者UID/userPosts/postID/comments,偏离了期望的posts/发帖人UID/userPosts/postID/comments结构,最终评论被存入错误的集合下。

修复方案

  1. 给函数新增postAuthorId参数,用来传入目标帖子的发帖人UID;
  2. 将Firestore路径中的.doc(authorId)替换为.doc(postAuthorId),确保指向正确的发帖人集合;
  3. 原参数authorId改为commenterId,明确表示这是评论者的UID,避免混淆。

修改后的代码如下:

Future<String> postComment(String postId, String text, String commenterId,
    String name, String profilePic, String postAuthorId) async {
  String res = 'Some Error occurred';
  try {
    if (text.isNotEmpty) {
      String commentId = const Uuid().v1();
      await FirebaseFirestore.instance
          .collection('posts')
          .doc(postAuthorId) // 指向帖子作者的UID
          .collection('userPosts')
          .doc(postId)
          .collection('comments')
          .doc(commentId)
          .set({
        'profilePic': profilePic,
        'name': name,
        'uid': commenterId, // 存储评论者的UID
        'text': text,
        'commentId': commentId,
        'datePublished': DateTime.now()
      });
      res = 'success';
    }
  } catch (e) {
    res = e.toString();
  }
  return res;
}

调用说明

调用该函数时,需确保postAuthorId传入的是目标帖子创建者的UID,commenterId传入当前评论用户的UID。无论评论自己还是他人的帖子,评论都会被存入正确的comments子集合中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 18:40:45