Felipe
Felipe

Reputation: 11959

Iterate all items in Firestore collection by key with pagination

I thought this one would be easier but it's not happening so far. I would like to iterate through all items in a collection without downloading every single item in one go.

Suppose my collection is at the ref /users and each user entry has a key as a username, such that you end up with

/users/
       jonsmith89: {}
       janedoe_: {}
       ...

I don't have a field to orderBy() since there are embedded collections contained in those objects and as such the docs for Pagination are not helping me. This is what I have so far

async IterateCollection(path, dataFunction, limit = 10) {
    let collection = this.db.collection(path)
        .limit(limit);

    let current = collection;
    let entries = 0;

    do {
        let snapshot = await current.get();

        // Do something with snapshot.docs......

        let last = snapshot.docs[snapshot.docs.length - 1];
        current = collection.startAfter(last.data())

        entries = snapshot.size;
    } while (entries > 0);
}

what I get is an exception:

Too many cursor values specified. The specified values must match the orderBy() constraints of the query.

Which kind of makes sense, but how can I order it by id(key) then? I tried a blank orderBy() as well as orderBy('id') even though there is no id field

Upvotes: 2

Views: 1411

Answers (1)

Wiliam
Wiliam

Reputation: 3754

The startAfter method needs the DocumentSnapshot, not the data.

startAfter(snapshot: DocumentSnapshot): Query;

So you have to remove the .data()

current = collection.startAfter(last)

Upvotes: 1

Related Questions