Search code examples
javascriptwhere-clauseindexeddbdexie

DexieJS (indexedDB) chain multiple .where clauses


I'm using DexieJS to fetch data from an IndexedDB. I've done the following tests both with v. 1.1.0 and 1.2.0.

It is working great for simple queries, but unfortunately I am unable to chain multiple where clauses.

First, I've tried this

var collection = db[table];
collection = collection.where('Field').equals("1");
return collection.count();

And that was working. Then, I need to add a where clause, but only if a given value is set:

var collection = db[table];
collection = collection.where('Field').equals("1");
if(value) collection = collection.where('Field2').above(value);
return collection.count();

This one fails. For test purposes, I've also tried:

var collection = db[table];
collection = collection.where('Field').equals("1")
.and('Field2').above(value);
return collection.count();

var collection = db[table];
collection = collection.where('Field').equals("1")
.and().where('Field2').above(value);
return collection.count();

var collection = db[table];
collection = collection.where('Field').equals("1")
.where('Field2').above(value);
return collection.count();

None of these work. I'm starting to think that this is not possible at all, but since the method and() exists, there must be a way!

PS this works:

var collection = db[table];
collection = collection.where('Field2').above(value);
return collection.count();

Solution

  • DexieJS' AND operator is implemented either as a filter function or a compound index. The simple way to implement your query is to use the filter method, something like;

    var collection = db[table];
    collection = collection
        .where('Field').equals("1")
          .and(function(item) { return item.Field2 > value });
    return collection.count();
    

    This means that the first filter will run against IndexedDB, and the additional condition will be run against each found item by DexieJS, which may or may not be good enough for what you need.

    As to how to use the compound index, it's a bit harder to apply to your exact situation without more details on the collections and exact queries you want, but there is much more information available here.