0

I want to retrieve data on with this value 7hmpcTuCAYQAYRqP7RNmnegSd9r2

But i'm getting all four objects in snapshot. I want to get parent key values which contain this key 7hmpcTuCAYQAYRqP7RNmnegSd9r2 Need to get blue mark keys.

Here is my code

     let ref = FirebaseManager.refs.databaseRoot.child("new_ChatListMembers")
    ref.queryOrdered(byChild: (Auth.auth().currentUser?.uid)!).queryEqual(toValue: true)
    ref.observeSingleEvent(of: .value) { (snapshot) in
        print(snapshot)
    }

This code return four objects instead of two.Please help me how i can get specific data. Thanks

enter image description here

Adnan Majeed
  • 141
  • 12

1 Answers1

1

You're not actually using the query that you construct in your code. To use that, it'd be something like:

let ref = FirebaseManager.refs.databaseRoot.child("new_ChatListMembers")
let query = ref.queryOrdered(byChild: (Auth.auth().currentUser?.uid)!).queryEqual(toValue: true)
query.observeSingleEvent(of: .value) { (snapshot) in
    print(snapshot)
}

But this won't actually scale very well, as you'll need to define an index for each individual UID value in this structure. In short: your current data structure makes it each to find the users for a specific chat room, but it doesn't help finding the chat rooms for a specific user.

To allow the latter, you'll want to add an extra structure in your data:

user_chats: {
  "$uid": {
    "$chatid": true
  }
}

So this is pretty much the inverse of what you have already, which is why this is often called an inverse index.

For more on this, and another example, see my answer here: Firebase query if child of child contains a value

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thank you for you response. Actually i was trying to follow this structure https://firebase.google.com/docs/database/web/structure-data#flatten_data_structures – Adnan Majeed May 20 '20 at 21:53
  • 1
    And that structure works great for when you only want to load the members for a room. If you also want to load the rooms for a member, you'll need what I show here and in the link. It is just another flat list in addition to the one(s) you already have. – Frank van Puffelen May 20 '20 at 21:55
  • Thank you so much. I'll follow your guide in above mentioned link. Cheers – Adnan Majeed May 20 '20 at 22:32