Justin Spring
Justin Spring

Reputation: 37

How to get range of documents

Let's say I've got 100 documents in my collection. My goal is to get the documents between 5 and 33.

I tried startAt and endAt but it didn't work:

  const db = firebase.firestore();

  await db
    .collection("pictures")
    .startAt(start)
    .endAt(end)
    .get()

Upvotes: 0

Views: 140

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317760

What you're trying to do isn't really possible. Documents don't have a natural index or position within a collection. To get ordering within a collection, you need to use at least one field on which you want to sort the documents. Only then do they have an order, and only then can you page through them.

The startAt and endAt methods on the query require that you define some order. You can see that in the example code provided in the API docs I linked to. Note the following statement in the docs for startAt:

Creates and returns a new Query that starts at the provided set of field values relative to the order of the query. The order of the provided values must match the order of the order by clauses of the query.

Upvotes: 3

Related Questions