MordsithM
Convex Community2y ago
1 reply
Mordsith

Sort paginated items

I have this schema

export const participantsSchema = defineTable({
  sessionId: v.id("session"),
  searchable: v.optional(v.string()),
  userProfileId: v.optional(v.id("userProfiles")),
  invitedBy: v.optional(v.id("userProfiles")),
  role: sessionRoleEnumValidator
})
  .index("by_session_id", ["sessionId"])
  .index("by_session_role", ["sessionId", "role"])
  .index("by_user_profile_id", ["userProfileId"])
  .index("by_user_profile_role", ["userProfileId", "role"])
  .index("by_invite", ["invitedBy", "userProfileId"])
  .index("by_invite_role", ["invitedBy", "userProfileId", "role"])
  .index("by_session_and_user", ["sessionId", "userProfileId"])
  .index("by_searchable_field", ["searchable"])
  .searchIndex("by_searchable", {
    searchField: "searchable",
    filterFields: ["userProfileId", "sessionId", "role"],
  });


I want to query like this but give the users ability to sort in ascending / descending order based on the searchable index.

const data = await ctx.db
        .query("participants")
        .withIndex("by_user_profile_role", (q) =>
          q.eq("userProfileId", userProfileId).eq("role", defaultRole)
        )
        .order("desc")
        .paginate(paginationOpts);


When I replace:

.withIndex("by_user_profile_role", (q) =>
          q.eq("userProfileId", userProfileId).eq("role", defaultRole)
        )


with:

.withIndex("by_searchable")


sort works as expected but I can't use multiple index, I need to use the existing index while allowing users to sort based on the searchable field
Was this page helpful?