Firestore评论添加异常:跨用户评论未存入指定子集合
问题分析与解决方案
问题根源
当前代码构建Firestore路径时,使用的authorId是评论者的UID,而非目标帖子的发帖人UID。这导致评论他人帖子时,路径变为posts/评论者UID/userPosts/postID/comments,偏离了期望的posts/发帖人UID/userPosts/postID/comments结构,最终评论被存入错误的集合下。
修复方案
- 给函数新增
postAuthorId参数,用来传入目标帖子的发帖人UID; - 将Firestore路径中的
.doc(authorId)替换为.doc(postAuthorId),确保指向正确的发帖人集合; - 原参数
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
相关产品推荐
相关产品推荐

