How can document references be used for Firestore API's [runQuery.startAt]?

Viewed 255

When using the Firestore REST API to order and filter results, I am unable to use a cursor/reference value for the startAt value. I feel this may be possible, seeing it is provided in examples of Firestore's cursor-based pagination is detailed in their SDK: https://firebase.google.com/docs/firestore/query-data/query-cursors

I have a query that uses orderBy on a integer field within a document. I can successfully start at a specific integer value for this query, like so:

"structuredQuery": {
    "from": [
        {
            "collectionId": "objects"
        }
    ],
    "orderBy": [
        {
            "field": {
                "fieldPath": "counter"
            },
            "direction": "DESCENDING"
        }
    ],
    "startAt": {
        "values": [
            {
                "integerValue": 15
            }
        ]
    }
}

I'm hoping to benefit from cursor pagination, but unfortunately if I change the startAt value to referenceValue, the query results do not reflect this, even though the query is successfully performed.

"startAt": {
    "values": [
        {
            "referenceValue": "projects/.../databases/(default)/documents/objects/OjvmBvvQ9TkyyQiJ4ExJ"
        }
    ]
}

Am I missing something in the way this works differently to the SDK examples?

1 Answers

Note that it's not a document reference but a document snapshot that you can use as a query cursor. A snapshot includes the field values needed for startAt. The SDKs take a document snapshot, extract the field values, and pass those values to startAt.

You can see the Node.js client library doing this here in createCursor and extractFieldValues.

Related