0

I got instagram like app. I got firebase as backend which has :

post node - contains all the posts from different users [post_id post_user post_name post_content]

Problem: I want to get the posts only from the users which I have followed.

My Steps:

  1. I got list of following users_id in array

    followersIds
    
  2. I want to know if I can make query like

    getFollowersList { (followersIds) in
    
        print(followersIds)
    
        self.postRef.queryOrdered(byChild: "user").queryEqual(toValue: followersIds).queryLimited(toLast: limit).observeSingleEvent(of: .value, with: { (snapshot) in
            if snapshot.value is NSNull { completion(nil); return}
            else {
                let dict = snapshot.value as! [String:Any]
                self.mapDictionaryToArrayOfPost(dict: dict, completion: { (posts) in
                    completion(posts)
                })
            }
        }) { (error) in
            debugPrint(error.localizedDescription)
        }
    
    }
    

ISSUE: Firebase can't accept array as parameter in queryEqual()

I can do this filter by filtering in the app but i want to query firebase and get the result . Beacause filtering in the app is not a good thing.

Any suggestion.

user3804063
  • 809
  • 1
  • 14
  • 32

1 Answers1

2

There is no way to do this query in one go in Firebase. As is common in most NoSQL solutions, you should model the data in a way that allows the use-cases that your app needs.

This means that: if you want to retrieve all posts from people you follow in one go, you should keep a list of all posts from people you follow in the database. Since you seem to be building something like a social network, that means that you're essentially building each user's wall:

following
  uid1
    uid2: true // so uid1 follows uid2 and uid3
    uid3: true
  uid3
    uid2: true // and uid3 follows uid2
posts
    post1 
      author: uid2 // uid2 has made a post
      title: "...." 
    post2 
      author: uid3 // uid3 has made a post
      title: "...." 
wall
  uid1
    post1: true
    post2: true
  uid3
    post1: true

So in this model we keep the key of each post of a user that you follow under /wall/myuid. Now you can easily get the list of posts to show the wall of a specific user. And from that you can loop over the keys and load each of them. The latter is not a slow operation on Firebase, since it pipelines the requests. See Speed up fetching posts for my social network app by using query instead of observing a single event repeatedly.

This type of data duplication is very common in NoSQL databases such as Firebase, which is why we cover it in our documentation on structuring data, in our firefeed demo app and in our new video series Firebase for SQL developers.

Community
  • 1
  • 1
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807