johnerfx johnerfx - 1 month ago 19
Javascript Question

What would be the proper way to store objects in firebase to reorder them later in an easy way?

I have a list like this

{"ids": [
{
"id1": {
"name": "name1",
"lastname": "lastname1"
}
},
{
"id2": {
"name": "name2",
"lastname": "lastname2"
}
},
{
"id3": {
"name": "name3",
"lastname": "lastname3"
}
},
{
"id4": {
"name": "name4",
"lastname": "lastname4"
}
}
]
}


Then I retrieve and display it with this:

import {Component} from '@angular/core';
import {AngularFire, FirebaseListObservable} from 'angularfire2';

@Component({
selector: 'app',
templateUrl: `
<ul>
<li *ngFor="let id of ids | async">
{{ id.name }}
</li>
</ul>
`,
})
class AppComponent {
ids: FirebaseListObservable<any>;
constructor(af: AngularFire) {
this.ids = af.database.list('/ids');
}
}


The result:

name1
name2
name3
name4


Let's say I would like to reorder/move some objects, so I get result like this:

name3
name1
name2
name4


What would be a good way to structure my objects to easily achieve this?
I could add "order" property, update it and order the query by "order" property.

this.ids = af.database.list('/ids',{
query: {
orderByChild: 'order'
}
});


Or maybe I could add previous id key as a property, but how to display the list then, taking "previous" property into consideration? I figure out how to achieve this to avoid future scalability issues.

Answer

First, you will have to add property for storing order.

Second, you should not be saving this data as array as firebase stores it as object anyway. Instead you should be saving as object.

Check out the following link for more info.

https://firebase.googleblog.com/2014/04/best-practices-arrays-in-firebase.html

So, your firebase database should look this.

"ids": {
    "id1": {
        "name": "name1",
        "lastname": "lastname1",
        "order": 1
    },
    "id2": {
        "name": "name2",
        "lastname": "lastname2",
        "order": 2
    },
    "id3": {
        "name": "name3",
        "lastname": "lastname3",
        "order": 3
    },
    "id4": {
        "name": "name4",
        "lastname": "lastname4",
        "order": 4
    }
}

And you should be querying by order property.