1

I have a database with the following structure

"users":{
    "user1234" {
       "username": "user1234" 
    }
}

I am trying to do a query to find a user with username "user1234". When I use queryEqual(toValue:) I don't get any matches but when using queryStarting(atValue: ) I do get the user. I have confirmed that the username is actually "user1234". What am I doing wrong?

let query1 = databaseRef.child("users").queryOrdered(byChild:"username").queryStarting(atValue: "user1234").queryLimited(toFirst: 1) 
query1.observeSingleEvent(of: FIRDataEventType.value, with: { (snapshot) in 
    //snapshot contains the user with username "user1234"
})

However the following does not work

let query2 = databaseRef.child("users").queryOrdered(byChild:"username").queryEqual(toValue: "user1234")    
query2.observeSingleEvent(of: FIRDataEventType.value, with: { (snapshot) in 
    //snapshot DOES NOT contain the user with username "user1234"
})

My security rules are

"rules": {
   ".read": "true",
   ".write": "true",      
   "users": {
     "$uid": {
       ".indexOn": ["username"],
     },
   },
 },
Nilsymbol
  • 515
  • 1
  • 9
  • 25

1 Answers1

0

You're facing this issue because query goes only one level deep, so you need to flatten your data or you have to figure out a different approach. Here you can find more detailed answer.

Community
  • 1
  • 1
i6x86
  • 1,557
  • 6
  • 23
  • 42
  • My first query works while the second one doesn't even though they are on the same level so there is no logical reason why the depth should change anything in my case – Nilsymbol Mar 05 '17 at 03:18
  • just tried it and it works fine. may be you have problems with your index. what does your security rules looks like? – i6x86 Mar 05 '17 at 15:15
  • 2
    give a try to: `"users": { ".indexOn": ["username"] }` without the uid – i6x86 Mar 05 '17 at 16:19
  • also, can you post a screenshot of your DB, or at least of the part with the "users" node? – i6x86 Mar 05 '17 at 16:26
  • That seems to have solved it! Don't fully understand why the other query produced the right results though but somehow it is working now. – Nilsymbol Mar 05 '17 at 16:40
  • @Nilsymbol ok i tried it and it has to do with the answer i gave you. i don't know why yet, but querying by queryStarting leaves you go one (or more level) deeper than querying by queryEqual, when you do it this way you go only one level deep, so if i were you i'll start to consider flattening the DB. – i6x86 Mar 05 '17 at 16:45