Filtered paginated list with firebase

2020-05-07 04:41发布

问题:

I'm trying to make a paginated filtered list with firebase and swift (but feel free to answer with the programming language that you like the most) without filter the retrieved data on the client.

Let's suppose I've this structure

matches
  match-1
    name: "Match 1"
    users
        user-1: "ok"
        user-2: true
  match-2
    name: "Match 2"
    users
        user-1: "ok"
        user-2: true
        user-3: true
  match-3
    name: "Match 3"
    users
        user-1: true
        user-2: true
        user-3: true
...

Now I want to get a paginated list of all the matches of the user-1 that have the value "ok"

I'm doing something like this

matchesRef
        .queryOrdered(byChild: "users/user-1")
        .queryEqual(toValue: "ok")
        .queryStarting(atValue: "<last-fetched-user-id>")
        .queryLimited(toFirst: 5)
        .observe(.value, with: { snapshot in

});

But it causes a crash because "Can't call queryStartingAtValue: after queryStartingAtValue or queryEqualToValue was previously called"

Any suggestions?

回答1:

If I recall correctly, you can pass in the key of the first item to return as a second argument to queryStarting. From the documentation (emphasis mine):

queryStartingAtValue:childKey: is used to generate a reference to a limited view of the data at this location. The FIRDatabaseQueryinstance returned by queryStartingAtValue:childKey will respond to events at nodes with a value greater than startValue, or equal to startValue and with a key greater than or equal to childKey.

So in code that would then be:

matchesRef
    .queryOrdered(byChild: "users/user-1")
    .queryStarting(atValue: "ok", childKey: "<last-fetched-user-id>")
    .queryLimited(toFirst: 5)
    .observe(.value, with: { snapshot in