2

I want to get all the users that are friends of the logged user. This is my data structure.

{
  "users": {
    "UID1":{
        "name":"Pepito",
        "friends":{
            "UID2":true,
            "UID4":true,
        }
     }
     ...
  }
}

I am getting the users with this code

Firebase.database.reference().child("users")
        .orderByChild("friends/" + Firebase.user.uid).equalTo(true)

And the rules should be

{
  "rules": {
    "users" : {
      ".read" : "query.orderByChild.contains('friends/')",
      "$uid" : {
            ".write": "auth.uid == $uid",
      }
    }
  }
}

But the rules not working, I am getting this error when I try to save

Error saving rules – Line 6: Invalid property access: target is not an object.

The line 6 is

".read" : "query.orderByChild.contains('friends/')",

I also tried with

".read" : "query.orderByChild == 'friends/'+auth.uid",
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
rterrani
  • 526
  • 2
  • 10
  • 1
    I'm not sure if this type of secure query is possible, but that last snippet looks what I'd use. What was the error/problem with that last rule? – Frank van Puffelen Jun 16 '18 at 14:02
  • 1
    In general I'd model the inverse collection too, so that you can just read `/users/peopleThatHaveFriendedMe`. See https://stackoverflow.com/questions/40656589/firebase-query-if-child-of-child-contains-a-value – Frank van Puffelen Jun 16 '18 at 14:03
  • This is the error in the last one `Error saving rules – Line 6: Invalid == expression: right operand must be an ordering or string literal when comparing against an ordering.` I saw your answer in the other question, but I want to list in one query all the users, that's not possible with the structure that you recommend, with that structure I need to do a query to get the id of the users, and then one query per user, right? – rterrani Jun 17 '18 at 04:29
  • Ok I found other of your answers that explains that this is a normal thing in firebase, and how the requests are done. https://stackoverflow.com/questions/35931526/speed-up-fetching-posts-for-my-social-network-app-by-using-query-instead-of-obse/35932786#35932786 – rterrani Jun 17 '18 at 04:48
  • 1
    Unfortunately the query you want to do simply isn't possible. You'll need to set up a structure that allows the query you want, so if you want to get the friends of the current user, you'll need to store that information in your data model. – Frank van Puffelen Jun 17 '18 at 04:48

0 Answers0