A. Ilazi A. Ilazi - 2 months ago 28
JSON Question

Firebase 3 orderByChild not working with ionic2

I am trying to retrieve data from my firebase database but I am not possible to sort the data by a child value.

data.db.orderByChild('likes').on('value', data => {
this.posts = data.val();
this.posts = Object.keys(this.posts).map(key => this.posts[key])
console.log(this.posts);
});


Here is my Service for data

this.db = firebase.database().ref('/posts');


and here my structure of the database

{
"posts": {
"1473631200000": {
"date": "12.02.2016",
"imageUrl": "http..."
"userId": "id",
"likes": 20
}
"1473804000000": {
"date": "12.08.2016",
"imageUrl": "http..."
"userId": "id",
"likes": 284
}
}
}


I am possible to retrieve the data but I cant sort them by the value of likes. I just want the top posts to be more in the front.

Answer

If you execute a query against the Firebase Database, it returns a DataSnapshot. That snapshot contains the keys, values and the order of the children.

When you retrieve a val() from the snapshot, it converts it to dictionary of keys and values. It loses the ordering in this case.

To keep the ordering, loop over the DataSnapshot using forEach and only then get the value:

data.db.orderByChild('likes').on('value', data => {
    this.keys = []'
    this.posts = [];
    data.forEach(child => {
        this.keys.push(child.key);
        this.posts.push(child.val());
    });
    console.log(this.posts);
});
Comments