livi1717 livi1717 - 3 months ago 50
Javascript Question

Firebase date-range query not working

I'm trying to do two separate queries from Firebase. The first is just a general query that gets the total number of entries saved. That works correctly.

The second one is supposed to be a time based range query that determines all of the entries saved for just this year.

The first query is working. The second is displaying "null" in the console. It should also display "10" as all the queries were created in 2016.

var ref = new Firebase('https://xxxxxxxx.firebaseio.com/entries');
ref.once('value', function(snapshot) {
$scope.allEntries = snapshot.numChildren();
console.log('Total entries saved to date: ' + $scope.allEntries);
// shows 10 entries, which is correct
});

var ref2 = new Firebase('https://xxxxxx.firebaseio.com/');
ref2.child('entries')
.startAt(14516244) // January 1st, 2016
.endAt(1472131318) // current date (aug, 25th 2016)
.once('value', function(snapshot) {
console.log(snapshot.numChildren());
// shows "null"
});


Here is a look at the timestamps from the first entry and the last entry.

enter image description here

Answer

You are missing orderByChild() in your second query.

Add it at the beginning of the query:

ref2.child('entries')
    .orderByChild('createdAt')
    .startAt(14516244) // January 1st, 2016
    .endAt(1472131318) // current date (aug, 25th 2016)
    .once('value', function(snapshot) {
            console.log(snapshot.numChildren());
            // shows "null"
});

Edit:

Second problem is that your dates in query are too small, because they are in seconds and your createdAt is in miliseconds. Convert it.

ref2.child('entries')
    .orderByChild('createdAt')
    .startAt(14516244000) // January 1st, 2016
    .endAt(1472131318000) // current date (aug, 25th 2016)
    .once('value', function(snapshot) {
            console.log(snapshot.numChildren());
            // shows "null"
});