I am implementing basic pagination but startAfter isn't working as intended. I have attached a snippet of my function which returns the desired documents and the last document.
The first query is working fine and correct last document object is being returned. However, the second time I run this function with lastVisible variable set to the previously returned object the function returns exactly the same values as the first execution even though the else statement containing startAfter is executed.
I am using firebase-admin that's why I am not using newer methods like getDoc etc.
export const fetchPosts = async (lastVisible, uid) => {
if (!admin.apps.length)
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
})
const db = getFirestore()
try {
let querySnap
if (lastVisible === null)
querySnap = await db.collection("posts").where("userId", "==", uid).orderBy("time", "desc").limit(2).get()
else {
querySnap = await db.collection("posts").where("userId", "==", uid).orderBy("time", "desc").startAfter(lastVisible).limit(2).get()
}
const lastDoc = querySnap.docs[querySnap.docs.length - 1]
// console.log(typeof lastDoc)
const docSnaps = querySnap.docs
let data = []
for (let i in docSnaps) {
// console.log(docSnaps[i].data())
data.push(docSnaps[i].data())
}
// console.log(data)
// console.log(lastDoc)
return { lastDoc: lastDoc, docs: data }
} catch (e) {
console.log(e)
}
}
This is what the lastDoc value is after first execution (some values have been altered by me here)
{
_fieldsProto: {
title: { stringValue: 'test', valueType: 'stringValue' },
time: { integerValue: '1656157500080', valueType: 'integerValue' },
userId: {
stringValue: 'YHX',
valueType: 'stringValue'
},
postId: { stringValue: 'dJ4QY', valueType: 'stringValue' },
text: {
stringValue: 'ship',
valueType: 'stringValue'
}
},
_ref: {
_firestore: { projectId: 'project-t' },
_path: {
segments: [Array],
projectId: 'project-t',
databaseId: '(default)'
},
_converter: {}
},
_serializer: { allowUndefined: false },
_readTime: { _seconds: 1656332177, _nanoseconds: 366724000 },
_createTime: { _seconds: 1656157500, _nanoseconds: 603745000 },
_updateTime: { _seconds: 1656157500, _nanoseconds: 603745000 }
}