I am just getting into using firebase. I have a document with 6 records indexed by id. I would like to query and sync the first 3 items in the list.
var metals = new Firebase("https://<dbname>.firebaseio.com/metals").limit(3);
$scope.metals = $firebase(metals);
This provides the last 3 items in the list. Not what I wanted.
So to get the first 3 items, I thought that this would work, but it breaks...
var metals = new Firebase("https://<dbname>.firebaseio.com/metals").startAt(1).endAt(3);
$scope.metals = $firebase(metals);
My data structure:
{
"metals" : [ null,
{
"id" : 1,
"metal" : "Aluminium",
"element" : "Au"
}, {
"id" : 2,
"metal" : "Silver",
"element" : "Ag"
}, {
"id" : 3,
"metal" : "Copper",
"element" : "Cu"
}, {
"id" : 4,
"metal" : "Tin",
"element" : "Sn"
}, {
"id" : 5,
"metal" : "Nickel",
"element" : "Ni"
}, {
"id" : 6,
"metal" : "Iron",
"element" : "Fe"
}]
}
HTML view:
The first parameter passed into startAt is a priority, not a record key. Since it doesn't look like you need a key or a priority in this case, you can simply this syntax to snag the first three items:
new Firebase(URL).startAt().limit(3)
Additionally, the "id" stored in each record of the example data is not the key for that record, it's just another field in the data and might as well be "foo" or any other arbitrary moniker, as far as querying is concerned.
When these records get stored in Firebase, the array is converted to an object, and the indices are used as the keys for each entry. So the first record's id would be 0, not 1. So if I wanted to grab the second through fourth records (e.g. 1 through 3 as you attempted), I could do this:
new Firebase(URL).startAt(null, 1).limit(3)
Please have a thorough read of the lists of data doc and our blog on array best practices; most of the time, you'll want to avoid those and use unique ids.
来源:https://stackoverflow.com/questions/24259562/angularfire-firebase-query-sync-first-x-items-in-document