Search code examples
where-clausedexie

Dexie not a function in where clause


I'm trying to query a Dexie DB to retrieve the top 25 most used items from a language-specific collection, below is the code and the issue I have found.

TABLE Schema:

myTable: 
      ++id,
      name,
      lang,
      lastUse,
      counter,
      [lang+counter],
      type,
      groupID,
      category_id,
      subcategory_id`

QUERY:

collection_result = dexieDB.myTable.where('lang').equals(`${active_language}`).reverse().sortBy('lastUse').limit(25);
collection_result.toArray();

ISSUE found:

caught (in promise) TypeError: dexieDB.myTable.where(...).equals(...).reverse(...).sortBy(...).limit is not a function

Solution

  • Unlike Collection.orderBy(), Collection.sortBy() returns a promise directly with the results so there's unfortunately no option to add a limit.

    But good news is you can both query and sort using a native index instead.

    1. Add the index '[lang+lastUse]'
    2. Do the following query:
      dexieDB.myTable
        .where('[lang+lastUse]')
        .between(
          [active_language, Dexie.minKey],
          [active_language, Dexie.maxKey])
        .reverse()
        .limit(25)
        .toArray();
      

    Reason you get it sorted by lastUse is that IndexedDB will always sort by the queried index, and the index we use is a compound index that includes the lastUse property. The .reverse() will make it sort in reverse order.