Using Firebase .startAt() and .endAt() query methods for date ranges

kevinius picture kevinius · Apr 21, 2015 · Viewed 10k times · Source

I'm using firebase in combination with GeoFire, this works great but I need one more query and I'm not sure how it should be done.

This is my GeoFire/Firebase query:

var geoFire = new GeoFire(ref.child("geoFire"));

var geoQuery = geoFire.query({
    center: [51.315077, 3.73261],
    radius: 100 //kilometers
})

geoQuery.on("key_entered", function(key, location, distance) {

    ref.child("articles").child(key).on("value", function(snap){

        var x = snap.val()
        DATA.push(x)

    })

})

This is my json database in firebase:

geoFire

-JmE05U-Wbr5LGRSh0Z8
-JmE0COUFBRPZIBqwfYN

articles

-JmE05U-Wbr5LGRSh0Z8
   * ...
   * articlePostDate: 2015/04/26 08:00:00
   * ...
-JmE0COUFBRPZIBqwfYN
   * ...
   * articlePostDate: 2015/04/26 12:00:00
   * ...
-JmE0Iq7-uvrk5Tg_K8_
   * ...
   * articlePostDate: 2015/01/26 08:00:00
   * ...
-JmE0MrnstNv9d_8ozQ4
   * ...
   * articlePostDate: 2015/04/26 15:00:00
   * ...

The above GeoFire/Firebase query returns 2 articles (but could be 100+ articles), this is correct.

My question:

How can I extend the Firebase query below so that I can get records based on a range of articlePostDates? For instance, all GeoFire returned records with a post date between 2015/04/26 07:00:00 and 2015/04/26 16:00:00? I think it's with .startAt() and .endAt(), but I'm unsure how.

ref.child("articles").child(key).on("value", function(snap){

    var x = snap.val()
    DATA.push(x)

})

Thx for your advise.

Answer

Saeed D. picture Saeed D. · Apr 21, 2015

Before using startAt() or endAt(), you need to order your list with orederByChild().

Try the following code (The starting point is inclusive).

ref.child("articles")
.orderByChild('articlePostDate')
.startAt('2015/04/26 07:00:00').endAt('2015/04/26 16:00:00')
.on("value", function(snap){
    var x = snap.val()
    DATA.push(x)
})

For more information please refer to Firebase Query.startAt