Firebase Firestore子集合更新失败 求排查问题原因
问题根源与修复方案
核心问题:Firestore文档路径错误
你的评论数据实际存储在posts/{postId}/comments/{commentId}这个子集合路径下,但点赞评论的代码中,错误地直接访问了根集合comments,导致Firestore找不到对应文档(因为目标文档根本不在根comments集合里)。
修复步骤
1. 修改likeComment方法
给方法添加postId参数,构建正确的子集合访问路径:
// like comment Future<void> likeComment( String postId, String commentId, String uid, List commentLikes) async { try { if (commentLikes.contains(uid)) { await _firestore .collection('posts') .doc(postId) .collection('comments') .doc(commentId) .update({ 'commentLikes': FieldValue.arrayRemove([uid]), }); } else { await _firestore .collection('posts') .doc(postId) .collection('comments') .doc(commentId) .update({ 'commentLikes': FieldValue.arrayUnion([uid]), }); } } catch (e) { print(e.toString()); } }
2. 调用方法时传入postId
在UI层绑定点赞按钮的点击事件时,需要同时传入当前评论所属的postId和commentId,示例调用如下(根据你的实际UI代码调整):
FirestoreMethods().likeComment( currentPost.postId, comment.commentId, userUid, comment.commentLikes, );
逻辑验证说明
你手动在Firebase控制台添加commentLikes字段能生效,是因为操作的是posts/{postId}/comments/{commentId}下的正确文档,而之前的代码路径指向了根集合comments,两者不是同一位置,所以出现"文档未找到"的错误。
内容的提问来源于stack exchange,提问作者Cosmos92000
相关产品推荐
相关产品推荐

