How to get the previous document in Firestore

Viewed 124

I want to navigate through the next and previous post of my firestore collection. I have setup next post function. But I can't make the previous function.

Here is my next post query:

firestore()
      .collection('Posts')
      .orderBy(firestore.FieldPath.documentId())
      .startAfter(this.state.currentDoc)
      .limit(1)

But sadly, firestore doesn't work with .orderBy(firestore.FieldPath.documentId(), 'desc') I tried with:

firestore()
      .collection('Posts')
      .orderBy(firestore.FieldPath.documentId())
      .limit(1)

It goes to the very first document of the collection. Adding ascending order doesn't work here again.

Let me know if any further information is needed.

EDIT:

According to the answer, here is what I am trying, instead of id, I am using time of the post when it was created. The time format is like: 1625511322000

firestore()
      .collection('Posts')
      .orderBy('time', 'desc')
      .startAfter(this.state.currentDoc)
      .limit(1)
1 Answers

The .startAfter() method should do it in descending order as well.

firestore()
      .collection('Posts')
      .orderBy("docID", "desc")
      .startAfter(this.state.currentDoc)
      .limit(1)

Let's say you have 4 documents: Doc1, Doc2, Doc3 and Doc4.

In first case, passing Doc2 in startAfter will return Doc3. (assuming the DocIDs are in ascending order). Similarly to get the previous post, you can sort the list in descending order and use startAfter which should return Doc1.

However, it seems you cannot sort documents in descending order using the document ID as mentioned in this answer. So you would have to store the document ID in the document as a field and then sort it like this:

.orderBy("docID", "desc")

If you try sorting in descending order using the document ID, you'll end up getting an error prompting you to create an index but you can't create it. The Firestore console will return an error, "name only indexes are not supported"

Related