Shamseer Ahammed
Shamseer Ahammed

Reputation: 1947

How to apply limit and startAt to child items of firestore document

I'm trying to apply pagination in firestore, i need to take the first 5 items of (200 total items) from the items array in my hats doc from collections collection, and then on next click i need to get he next 5 and so on.

testPagination = async () => {

    const { currentPage, itemsPerPage } = this.state;
    const { fetchCollectionsForPagesStart, match : { params } } = this.props;
    const collectionId = params.collectionId;

    const startAt = currentPage * itemsPerPage - itemsPerPage;

    const docs =  await firestore.collection("collections").orderBy('id').startAt(0).limit(itemsPerPage).get();
    const data = docs.docs;

    const items = docs.forEach( async docItem => {
        console.log(await docItem.data());
    })
}

i run this function when i click a button in my render function inside react,

render()
{
    return (
        <button onClick={this.testPagination}>Test pagination </button>
    );
}

but i am always getting 200 items in my result, so how do i apply startAt() and limit() to items array in firestore.

This is my db :

enter image description here

This console.log(await docItem.data()); gives me

enter image description here

NB : I'm receiving the hats document id, so if there is a way to access hats with id in would want some help in that too i have tried

const docs = await firestore.doc(`collections/${collectionId}`).get();
const data = await docs.data();

But this doesn't allow me to apply startAt() and limit()

Upvotes: 0

Views: 448

Answers (1)

Chris Ch&#225;vez
Chris Ch&#225;vez

Reputation: 431

In your database, hats is a document of collections collection. In Firestore you can't bring a part of a document (5 items from your items array, for example) always brings all the document and it counts as one read in Firestore. If you want to make pagination on items array you must create a subcollection in hats with the data on items. Having this structure you can perform a startAtQuery() with a limit() of 5 documents, which in this case it counts as 5 reads in Firestore.

You can see all about the Firestore data model here: https://firebase.google.com/docs/firestore/data-model

Upvotes: 3

Related Questions