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
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.