Home > Software engineering >  Firebase Firestore Query v9 Works "desc" but not "asc" (indexed both)
Firebase Firestore Query v9 Works "desc" but not "asc" (indexed both)

Time:03-06

I am trying to order by price in both directions. However, it currently only works "desc" and not "asc".

The 'direction' variable is either set to "asc" or "desc" depending on button click. I have checked - it is definitely asc or desc.

The request returns 50 items on "desc" but returns an empty array on "asc". Surely this doesn't make sense as it is the same request reading the same data just in another direction.

    const reference = await query(
      collection(firestore, "assets"),
      where("status.locked", "==", true),
      orderBy("status.price", direction),
      limit(count),
      startAfter(lastVisible?.status?.price ?? "")
    );

This is how direction is initialised: (filtering either is "High to Low" or "Low to High")

let direction = filtering === "High to Low" ? "desc" : "asc";

CodePudding user response:

As we discovered in the comments, the value of lastVisible is not correct for an ascending sort in your case.

Since you're using startAfter(lastVisible?.status?.price ?? ""), you will need to find the inverted lastVisible object when you invert the sort order. Alternatively, you can invert the logic and use endBefore instead.

  • Related