issue with cloud firestore firebase query in flutter

Viewed 53

I haveposts(collection) -> userid(document) -> userposts(collection) -> postid(document) -> fields (postname,description)how can i perform search based on postname i want to get post from all users

i have following and followers collection

following -> userid(document)->userfollowing (collection) -> all the user ids(documents)

followers -> userid(document)->userfollowers (collection) -> all the user ids(documents)

I have a timeline page the current logged in user should be able to see all the post from users to whom he has followed

(i am ready to change the structure it this is not correct)

1 Answers

I have a timeline page the current logged in user should be able to see all the post from users to whom he has followed

In this case you would have to first fetch UIDs of all users that the current user has followed i.e. read the userfollowers sub-collection documents. If there is any limit on how many users can a user follow, I'd recommend storing those UIDs in an array in user's document itself so it won't cost you N reads everytime you fetch user's followers (N is number of users that this user follows.)

(i am ready to change the structure it this is not correct)

I'd recommend creating 2 different collections to store users and posts as shown below:

users -> {userId}
(col)     (doc)

posts -> {postId}
(col)     (doc)

You would have to store a field userId in each post containing the author's UID

Once you have fetched the UIDs, you would have to fetch posts of each user individually. You can use whereIn operator as shown below but that can be used only if you have at most 10 UIDs in the user followings list.

FirebaseFirestore.instance
  .collection('posts')
  .where('userId', arrayContainsAny: [...theArrayContainingUserFollowingsID])
  .get()
  .then(...);

However if you have more than 10 users in following, then you would have to fetch each user's posts individually or create batches of 10 and use arrayContainAny as shown above.

You can also paginate your data to save reads and fetch data that user has requested instead of all posts from user.

Related