Wisdom
Wisdom

Reputation: 1

how to use orderByChild with startAfter in Realtime Database using Node.js

I am trying to sort orders in descending and start after on particular key but its not working

nextAfter : -Mk4-n5BnVpwhum62n2g or any Key / _id

db record:

{
  '-Mk4-n5BnVpwhum62n2g': {
    _id: '-Mk4-n5BnVpwhum62n2g',
    createdAt: -1632171667626,
    name: 'abc'
  },
  '-Mk40Ko9DbSeMdjIpY4': {
    _id: '-Mk40Ko9DbSeMdjIpY4',
    createdAt: -1632171809831,    
    name: 'new '
  }
}

trying query :

query = dbRef.orderByChild('createdAt').startAfter(nextAfter).limitToFirst(limit);

Upvotes: 0

Views: 618

Answers (1)

samthecodingman
samthecodingman

Reputation: 26171

The startAfter() method accepts two parameters - the first is the relevant orderBy value and the second is the optional key of the last entry (for when multiple entries have the same value for the orderBy criteria). So to correctly paginate the reference, you need to pass the previous entry's createdAt value and its key.

const baseQuery = dbRef
  .orderByChild('createdAt')
  .limitToFirst(limit);

let pageCount = 0, lastChildOnPage = undefined;
const children = [];

while (true) {
  const pageQuery = pageCount === 0
    ? baseQuery
    : baseQuery
       .startAfter(lastChildOnPage.createdAt, lastChildOnPage.key);
 
  const pageSnapshot = await pageQuery.once('value');

  pageSnapshot.forEach((childSnapshot) => {
    children.push({ key: childSnapshot.key, ...childSnapshot.val() });
  })

  const newLastChildOnPage = children[children.length-1];

  if (lastChildOnPage !== newLastChildOnPage) {
    lastChildOnPage = newLastChildOnPage;
    pageCount++;
  } else {
    break; // no more data
  }
}

console.log(`Grabbed ${pageCount} page(s) of data, retrieving ${children.length} children`);

Upvotes: 3

Related Questions