Search code examples
node.jsfirebasegoogle-cloud-firestorefirebase-admin

Firestore admin pagination without parameters (Node.js)


I would like to paginate through all of the documents in one of my collections. However I don't need a search parameter like 'population' or any other one. I simply want to load all items in the collection in batches, in no particular order. The documentation only shows with a search parameter. If you need more insight let me know.


Solution

  • If you are referring to not using orderBy() method in your query then you can just omit that method. In that case your queries will be sorted in ascending order by document ID. You can still use limit() method to get first few documents and then use snapshot of the last document to get the next batch.

    let lastDocSnap = null
    
    async function getNextBatch(lastDoc) {
      const query = await db.collection('collection')
      if (lastDocSnap) query = query.startAt(lastDoc) // pass last doc snapshot
      query = query.limit(10) // add limit
      
      const snapshot = await query.get()
      lastDocSnap = snapshot[snapshot.size-1] // setting new last doc
      return snapshot.docs.map(doc => doc.data)
    }
    
    getNextBatch(lastDocSnap)
    

    As mentioned above, these will be sorted based on their document IDs as you are not explicitly specifying any field using orderBy.

    Use a document snapshot to define the query cursor