So my comments are getting added to the correct post when the comment is made by the author on their own post, like so enter image description here

The Firestore code updated test:

Future<String> postComment(String postId, String text, String authorId,
      String name, String profilePic) async {
    String res = 'Some Error occurred';
    try {
      if (text.isNotEmpty) {
        String commentId = const Uuid().v1();
        await FirebaseFirestore.instance
            .collection('posts')
            .doc(authorId)
            .collection('userPosts')
            .doc(postId)
            .collection('comments')
            .doc(commentId)
            .set({
          'profilePic': profilePic,
          'name': name,
          'uid': authorId,
          'text': text,
          'commentId': commentId,
          'datePublished': DateTime.now()
        });
        res = 'success';
      }
    } catch (e) {
      res = e.toString();
    }
    return res;
  }

The desired structure of how the comments should get added: posts>UID(of poster)> userPosts(List of their posts)>postID>append comment to this postId as a subcollection.

Now, when I try to create a comment on a post made by another user, a new collection gets started with the ID of the post as its collection name. The postId it gets is the CORRECT id, however, the actual comment itself doesn't get added to the collection of THAT post. As you can see from the circle in the second image, the IDs match, however, the comment made doesn't go where it's intended, as it does in the first image. Does anyone know how I can fix this?

enter image description here

Image with new code test, new collection gets made with the UID of the person who's post I am commenting on, doesn't get added to the subcollection of the actual postId

enter image description here


Solution 1: Alex Mamo

When you're using the following reference:

    await FirebaseFirestore.instance
        .collection('posts')
        .doc(uid)
        .collection('userPosts')
        .doc(postId)
        .collection('comments')
        .doc(commentId)

You're always trying to add data inside a document that corresponds to the currently authenticated user. That's the reason why when you are using the above code with another user, it writes the data to another location. Which location, the one that corresponds to that user.

If you want to write the data under a particular location, you have to create a reference that points to that particular location. For instance, if you want a user to write some data, in a document that corresponds to another user, you have to create a reference that contains that UID. That can be simply done, by adding the ID of the user who creates the post inside the document. In that way, doesn't matter which user reads the post, when you want to write the data, you can use the ID of the user who created the post, to construct the correct path.