When I get all the data from the database without any query, I get the last entries from the database (keys are generated to work this way). Something like this:
var ref = firebase.database().ref('myObj').limitToFirst(100);
ref.on("value", function(snap){
console.log(snap.val());
});
This way I get all the objects I need ordered properly. But if I add a query to filter some data, I lost the order from the original.
var ref = firebase.database().ref('myObj').orderByChild('myChild').equalTo('myproperty').limitToFirst(100);
ref.on("value", function(snap){
console.log(snap.val());
});
This way I am not receiving the most recent data as I get when I don't apply any filter.
How can I solve that?
I just realised what happens with this:
.ref('myObj').orderByChild('myChild').limitToFirst(100);
is that orderByChild('myChild') reads JSON in descending order (from the bottom) and then that list is queried again by limitToFirst(100) in ascending order ("queried again" - I mean maybe in a more efficient way than literally querying list again). So what was originally at the bottom, goes to the top - you get your 100 records starting from the bottom of your Firebase JSON file.
You can try it out (tested with AngularFire2 - remove orderByChild('size') to see the change in ordering).
Some ways to revert the order:
First way as you wrote, is simply change query to LimitToLast()
Other ways:
Revert pipe:
<div *ngFor="let item of listObservable | async | reverse">
Using AngularFre2, you could take advantige of Rxjs features:
this.stories = af.database.list('/myObj', {
query: {
limitToLast: 100
}
}).map((array) => array.reverse()) as FirebaseListObservable<any[]>;
Or one, interesting, way to reverse via CSS:
#container{
display: -webkit-flex;
display: -moz-flex;
display: -ms-flex;
display: -o-flex;
-webkit-flex-direction: column-reverse;
-moz-flex-direction: column-reverse;
-ms-flex-direction: column-reverse;
-o-flex-direction: column-reverse;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With