updating data in firebase Firestore

Viewed 15

I am learning firebase and I am creating application where user will authenticate himself/herself. And then he will make new post like faceBook. I have create collection with userData and a document with a specific userId. And I have one field named with post where I want to store the user post. But when the user shares a new post the old one replace with a new post. I know it should happen, but what should I do for it. Like I want to store all the posts. for example if the user shares the new post then I want to update the post Field.

Here is my method for storing the post.

Future<void> addPostToFirestore() async {
   
    DocumentReference documentReference = FirebaseFirestore.instance
        .collection('userData')
        .doc(UserProvider.user.uid);
    documentReference.set(
      PostData(post: postController.text).addData(), //PostData is the model class
      SetOptions(merge: true),
    );
  }

Model Class


class PostData {
  String post;
  PostData({
    required this.post,
  });
  Map<String, dynamic> addData() {
    return {
      'post': post,
    };
  }
}
1 Answers

But when the user shares a new post the old one replace with a new post… I want to store all the posts.

If I correctly understand your requirements you could use a subcollection under each user’s document. In this (sub)collection you store all the user’s posts as documents.

Something like:

collectionReference postCollReference = FirebaseFirestore.instance
        .collection('userData')
        .doc(UserProvider.user.uid)
        .collection('posts');
postCollReference.add(PostData(post: postController.text).addData());
Related