0

I have been trying to find out how to order documents by their IDs in ascending or descending order (doesn't matter) but couldn't find a single solution to that. I have found order by timestamp but don't want to do that as multiple documents could be created at the same time.

I need to order documents by their auto-generated id because I am implementing pagination:

retrieveMoreRestaurants = async () => {
        this.setState({
            refreshing: true,
        });
        var additionalQuery = await firebase.firestore().collection('restaurants')
            .orderBy('__name__')
            .startAfter(this.state.lastVisibleDiscount)
            .limit(this.state.limit)

        var documentSnapshots = await additionalQuery.get();
        var All = documentSnapshots.docs.map(document => document.data());
        var lastVisible = All[All.length - 1].res_id;
        this.setState({
            All: [...this.state.All, ...All],
            lastVisible: lastVisible,
            refreshing: false,
        });
};

1 Answers1

0

As it is stated in the official documentation:

By default, a query retrieves all documents that satisfy the query in ascending order by document ID.

Basically, if you need them in the ascending order regarding the ID, you should just implement the default query.

You can also check a large discussion on this topic in other StackOverflow post.

Andrei Tigau
  • 2,010
  • 1
  • 6
  • 17
  • I am doing this because I need to know the last fetched item: var additionalQuery = await firebase.firestore().collection('restaurants') .orderBy(firebase.firestore.FieldPath.documentId()) .startAfter(this.state.lastVisible) .limit(this.state.limit) –  Jan 04 '20 at 10:50