Limiting the firebase equalTo query with the optio

2019-07-30 18:03发布

问题:

I have a feeling I may have the understanding of this feature wrong coming from the SQL background. The documentation is sparse and I haven't been able to find a good example or an explanation. I am looking for a clarification to the following from https://github.com/angular/angularfire2/blob/master/docs/4-querying-lists.md:

1 The Firebase SDK supports an optional key parameter for startAt, endAt, and equalTo when ordering by child, value, or priority. You can specify the key parameter using an object literal that contains the value and the key. For example: startAt: { value: 'some-value', key: 'some-key' }.

I want to limit my ordered-by-timestamp-value query (orderByChild) using this optional key parameter to restrict the results only to those were a child key has a specified value.

this.angularFireDatabase.list('/items', {
  query: {
    orderByChild: 'uploadedOn_',
    equalTo: { key: 'user_uid', value: 'fSXX9twkttYqoS67mcRUmPawIep1' }
  }
});

// JSON 
{
  "items" : {
    "-KijNTXRKV5rjXEA7NdO" : {
      "uploadedOn_" : -1493296081615,
      "user_uid" : "fSXX9twkttYqoS67mcRUmPawIep1"
    },
    "-KijNoB4MivU4Ts6XgUV" : {
      "uploadedOn_" : -1493296169733,
      "user_uid" : "fSXX9twkttYqoS67mcRUmPawIep1"
    },
    "-KijbTMBydwQexbbErlk" : {
      "uploadedOn_" : -1493300012491,
      "user_uid" : "EAsIjLDFPRZDTq97qGQQyS7sBul1"
    }
  }
}

Perhaps, I'm trying to mimic the where SQL clause when instead I should be structuring my data differently. It seems that this optional key parameter can only be the item's own key. In my example it's the regular auto-generated Firebase push key (e.g. "-KijNTXRKV5rjXEA7NdO"). But in this case I'm confused as to what the use case would be to use equalTo together with orderByChild if the result will always be a single item you could get to by NOT using the optional key parameter.

回答1:

If you do ref.orderBy("prop").equalTo("value", "key") it'll give the same results as ref.child("key"). The second parameter for equalTo() is essentially useless (unlike for startAt() and endAt(), where it can be used to slice a range.

Also see:

  • Firebase Query order by and start at name
  • How to paging query from Firebase using Android FirebaseUI