Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine Firestore orderBy desc with startAfter cursor

i am trying to query a list in firestore that should be sorted by a descending date property and make use of a startAfter cursor to paginate the results.

As you can see in the snippets below, this is failing once i combine orderBy('date', 'desc') with startAfter(lastDoc.date).

I am wondering what i am doing wrong. Any ideas?

// this actually works
// but it is sorted by ascending dates
db.collection('tanks')
  .doc(tankId)
  .collection('documentations')
  .orderBy('date')
  .startAfter(lastDoc.date)
  .limit(pageSize)
  .get()
  
// this even works...
// but has no cursor (startAfter) set for pagination
db.collection('tanks')
  .doc(tankId)
  .collection('documentations')
  .orderBy('date', 'desc')
  .limit(pageSize)
  .get()
  
// this is what i need
// but it returns always zero results
db.collection('tanks')
  .doc(tankId)
  .collection('documentations')
  .orderBy('date', 'desc')
  .startAfter(lastDoc.date)
  .limit(pageSize)
  .get()
like image 584
user2458046 Avatar asked Jan 04 '18 14:01

user2458046


Video Answer


2 Answers

You need to pass the actual document snapshot to startAfter, not the date value:

db.collection('tanks')
  .doc(tankId)
  .collection('documentations')
  .orderBy('date', 'desc')
  .startAfter(lastDoc)
  .limit(pageSize)
  .get()

See the reference documentation for startAfter().

like image 89
Frank van Puffelen Avatar answered Sep 20 '22 15:09

Frank van Puffelen


This is actually working, no idea why it did not before...

const snapshot = lastDoc
  ? await Api.db.collection('tanks')
      .doc(tankId)
      .collection('documentations')
      .orderBy('date', 'desc')
      .startAfter(lastDoc.date)
      .limit(pageSize)
      .get()
  : await Api.db.collection('tanks')
      .doc(tankId)
      .collection('documentations')
      .orderBy('date', 'desc')
      .limit(pageSize)
      .get();
like image 43
user2458046 Avatar answered Sep 17 '22 15:09

user2458046