kossnocorp / typesaurus

🦕 Type-safe TypeScript-first ODM for Firestore
https://typesaurus.com
412 stars 34 forks source link

Paginated query with order by #127

Open Daplex opened 6 months ago

Daplex commented 6 months ago

Hi!

I've got an issue having a query working with a sort by.

  const dataPromise = typesaurus.companies.query(($) => [
    $.field(sortBy?.id ?? "createdAt").order(sortBy?.direction ?? "desc"),
    $.field($.docId()).order($.startAfter(after)),
    $.limit(pageSize),
  ]);

I'm trying to sort by a field and then paginate thanks to the docId of after which is the last element of the previous page.

The startAfter doesn't seem to work, maybe because there are two orderBy in the query.

I've managed to have this use case working with the firebase-admin sdk:

  let query = db
    .collection("companies")
    .orderBy(sortBy?.id ?? "createdAt", sortBy?.direction ?? "desc");

  if (after) {
    const afterDocument = await db.collection("companies").doc(after).get();
    query = query.startAfter(afterDocument);
  }

  const dataPromise = query.limit(pageSize).get();

Thanks for the help!

kossnocorp commented 6 months ago

Hey, @Daplex, thank you for reporting that, and sorry for the silence. I was on vacation. I will investigate and share a solution or publish an update that fixes it.

abubakir1997 commented 1 month ago

I am facing the same issue, the pagination doesn't work, it only repeats the same page. I tried it with vanilla firebase/firestore and passed the snapshot object and pagination worked just fine.

ProductCollection(context)
      .query(($) => [
        $.field('updatedAt').order('desc'),
        $.field($.docId()).order('desc', $.startAfter(lastProduct ? ProductId(context, lastProduct?.id) : undefined)),
        $.limit(30),
      ])
tjx666 commented 3 days ago

I use:

db.xxxx.query(($) => {
    return [
      $.field('created_at').order('desc'),
      ...(cursor ? [$.field($.docId()).order($.startAfter(cursor))] : []),
      $.limit(PAGE_SIZE),
    ];
  })

throw error:

The query requires an index. You can create it here: https://console.firebase.google.com/v1/r/project