how to fix error: 'No document to update' Firebase Flutter

how to fix error: 'No document to update' Firebase Flutter

我收到以下错误消息。

流关闭状态:状态{代码=NOT_FOUND,描述=没有要更新的文档:projects/improve-practice-app/databases/(默认)/documents/posts/postID,原因=null}。

当用户点击 post 的图像时,如果他们的用户 ID 不在点赞列表中,我想将他们的用户 ID 添加到 Firestore 中的点赞列表中。如果他们的用户 ID 已经在喜欢列表中,我想将其从喜欢列表中删除。在下面的代码中,我尝试使用 UUID 包 update/create 一个具有唯一文档 ID 的 'posts' 集合。

class FirestoreMethods {
  final FirebaseFirestore _firestoreDB = FirebaseFirestore.instance;

  Future<void> likePost(
      {required String postID,
        required String? uid,
        required List likes}) async {
    try {
      if (likes.contains(uid)) {
        await _firestoreDB.collection('posts').doc('postID').update({
          'likes': FieldValue.arrayRemove([uid]),
        });
      } else {
        await _firestoreDB.collection('posts').doc('postID').update({
          'likes': FieldValue.arrayUnion([uid]),
        });
      }
    } catch (err) {
      err.toString();
    }
  }
}

GestureDetector(
onDoubleTap: () async {
await FirestoreMethods().likePost(
postID: widget.snap?['postID'],
uid: appUser?.uid as String,
    likes: widget.snap?['likes'],
);
setState(() {
isLikeAnimating = true;
});
},

如何修复错误以便我可以为每个 post 分配一个唯一的 'postID' 然后获得对 'likes' 列表的访问权限?在此先感谢您的帮助。

很抱歉这个答案太简单了,但是...

await _firestoreDB.collection('posts').doc('postID').update({
          'likes': FieldValue.arrayRemove([uid]),
        });

您正在尝试更新名为“postID”的文档...

我猜你想写:

await _firestoreDB.collection('posts').doc(postID).update({
          'likes': FieldValue.arrayRemove([uid]),
        });

postID 两边没有引号...传递变量 postID,而不是字符串“postID”。