Search code examples
angularfirebasefirebase-realtime-databaselazy-loadingangularfire2

Firebase - Query based on partitioned offset logic


I'm creating a chat app in Angular 4 which stores and reads messages in and from the Firebase database.

I've written a query to retrieve only the latest 10 messages of that specific conversation.

this.messages = this.db.list('messages/' + conversationId, { query: { limitToLast: 10 } });

db: AngularFireDatabase, messages: FirebaseListObservable

Now I want to retrieve the 10 older messages when somene presses the 'more' button (or scrolls to the top) and I'm having difficulties writing a query for this.

This is what I tried:

this.messages = this.db.list('messages/' + conversationId, { query: { orderbyChild: 'id', startAt: start, limitToLast: 10 } });

'start' here is an id like '-KovtCl4hEUPR2LfQfpc', which is the id of the oldest message in the this.messages FirebaseListObservable. I've also tried to manually pass this ID as string to the method that executes the query above.

Trying to do it as described here:

  1. https://stackoverflow.com/a/43969460/5437768
  2. https://firebase.google.com/docs/reference/android/com/google/firebase/database/Query
  3. https://firebase.google.com/docs/database/web/lists-of-data#filtering_data

The last query gives me 0 results.

Firebase layout

/messages/conversationId/messageId/{message}

"messages": {
    "-k32b": {
        "-kT3d": {
            "content": "Hello World!",
            "id" : "-kT3d"
        },
        "-kT4c": {
            "content": "How are you World?",
            "id" : "-kT4c"
        }
    }
}

What am I doing wrong here?


Solution

  • It turns out it did not work because of a typo in the query ('orderbyChild' instead of 'orderByChild'). Thanks Firebase for not giving me any errors here:p

    I am now indeed using .orderByChild(), .endAt() and .limitToLast() together, in a method chain. This makes sure that the query-conditions are executed in the correct order, where as querying this in a query object seems to execute these conditions in no particularly order.