Search code examples
javascriptfirebasefirebase-realtime-databaseangularfire

Pagination With realtime database in firebase when Child is same


I am having a problem with pagination with firebase

I am retrieving a limit of 5 results each time:

Showing you the problem with an example will be easier:

"myDb":{
  "products": {
      "uid1" : {
        "name" : "hello",
        "uid"  : "uid1",
        "size" : "1"
      }
      "uid2" : {
        "name" : "hello",
        "uid"  : "uid2",
        "size" : "2"
      }
      "uid3" : {
        "name" : "hello",
        "uid"  : "uid3",
        "size" : "34"
      }
      "uid4" : {
        "name" : "hello",
        "uid"  : "uid4",
        "size" : "4"
      }
      "uid5" : {
        "name" : "hello",
        "uid"  : "uid5",
        "size" : "15"
      }
      "uid6" : {
        "name" : "hello",
        "uid"  : "uid6",
        "size" : "50"
      }
  }
}

of course this is not my real data but now let me show you my query, I am using angularfire.

  getDatasByQuery(path:string, query:string){
    return this.db.list(path, (ref) => {
        return (ref.orderByChild('name').startAt(query).limitToFirst(5))
    })
  }

So what I actually do is take thevalue of the name property in the last results and make another query with it to paginate. Only problem is that name equals to "hello" all the time.

of course I could increase the limit but the main problem would remain the same

I would like the user to search by name attribute and paginate results, as you might have understood at this moment the only thing I get are the 5 first results where name equals "hello" and never reach the sixth.

so

first query ==> ['uid1', 'uid2', 'uid3', 'uid4', 'uid5'] => second query => exactly the same results

any help is greatly appreciated, please let me know if you need more explanations.


Solution

  • The startAt method takes an optional second parameter, which is the key of the node to start at in case there are multiple matches for the first value.

    So if you want to start at uid4 after ordering on name and filtering on hello, that'd be:

    ref.orderByChild("name").startAt("hello", "uid4");
    

    The uid4 here is the key of the node to start at, typically referred to as a disambiguation key.