Home > database >  Paginate firebase realtime database
Paginate firebase realtime database

Time:10-24

I want to get the first document in my subscription collection and then use that document as the starting point to retrieve the next 10 documents. The reason why I am not retrieving the first 10 straight away is that I want to run a cron job to paginate the data and change the starting document for every job run.

static start: number = 1;
@Cron(CronExpression.EVERY_5_SECONDS)
async getAllTransaction(): Promise<void> {
    this.getAtIndex(TransactionsService.start).then(res => {
        const ref = database().ref('subscriptions').limitToFirst(10).startAt(res);
        ref.once('value').then(item => {
            console.log(item.val());
        });
    });
}

async getAtIndex(id: number): Promise<any> {
    const ref = database().ref('subscriptions').limitToFirst(1);
    const snapshot = await ref.once('value');
    const value = snapshot.val();
    return value;
}

But I get this error

throw new Error('Query: When ordering by priority, the first argument passed to startAt(), '

Error: Query: When ordering by priority, the first argument passed to startAt(), startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value (null, a number, or a string).

I have tried using an arbitrary number as the argument for the startAt() but it returns null

CodePudding user response:

Your res is a DataSnapshot, which is not a valid value to pass to startAt. You probably want to pass res.key instead.

const ref = database().ref('subscriptions').limitToFirst(10).startAt(res.key);

In addition: if you don't specify any orderBy... clause for a query, it is ordered by an outdated priority value. Since you most likely want to order by the key, use orderByKey() in all your queries.

  • Related