Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

162
Views
GCP Firestore pagination with node.js - query cursor without snapshots

I'm a bit confused with a documentation, where it says to use "Use a document snapshot to define the query cursor".

I have an API http://localhost:3001/products?page=3&perPage=2 where I want to provide a specific page to retrieve defined amount of data.

.startAfter(page * perPage - 1) is ignored and it just pops out the first data as by default.

Did I miss something ?

app.get('/products', async (req, res) => {
  console.log('====== ๐Ÿ†• ======')
  const db = new Firestore({ projectId: process.env.PROJECT_ID })

  const page = Number(req?.query?.page) || 1
  const perPage = Number(req?.query?.perPage) || 4

  const results = []

  const query = db.collection('orphans')
    .select('sku')
    .orderBy('sku')
    .limit(perPage)
    .startAfter(page * perPage)

  const collection = await query.get()

  collection.forEach(doc => results.push({ id: doc.id, ...doc.data() }))
  console.log(`Returned ${results.length} out of ${collection.size}`)
  console.log('First item:', results[0].id)
  console.log('Last item:', results[results.length - 1].id)

  return res.json({
    status: 'OK',
    data: results
  })
})

Console output:

====== ๐Ÿ†• ======
page: 3
perPage: 2
Returned 2 out of 2
First item: 000_TEST_MASS_001
Last item: 000_TEST_MASS_002
about 4 years ago ยท Juan Pablo Isaza
1 answers
Answer question

0

You're trying to use startAfter as an offset, passing in the number of items of how many documents to skip. That's not how startAfter works.

Firestore pagination is based on knowing the document that you want to start retrieving after, known as the anchor object - or a cursor. So instead of passing in a count, you're supposed to pass in either a snapshot of the document to start after, or the sku (the field you sort on) value and the document id of the document to start after.


Since you're running on Node.js, there is a function that does what you want called offset (see reference docs). When you use this operation though, be aware that you're charged for reading all documents that were skipped by the offset too.


I recommend also checking out some of these previous questions on Firebase pagination and offsets.

about 4 years ago ยท Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
ยฉ 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!