DexieJS(indexedDB)链接多个.where子句

don*_*don 3 javascript where-clause indexeddb dexie

我正在使用DexieJS从IndexedDB获取数据。我已经对1.1.0版和1.2.0版进行了以下测试。

它对于简单查询非常有用,但是不幸的是,我无法链接多个where子句。

首先,我已经尝试过

var collection = db[table];
collection = collection.where('Field').equals("1");
return collection.count();
Run Code Online (Sandbox Code Playgroud)

那是行得通的。然后,仅在设置了给定值的情况下,才需要添加where子句:

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

这个失败了。为了进行测试,我还尝试了:

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();
Run Code Online (Sandbox Code Playgroud)

这些都不起作用。我开始认为这根本不可能,但是由于该方法and()存在,因此必须有一种方法!

PS这工作:

var collection = db[table];
collection = collection.where('Field2').above(value);
return collection.count();
Run Code Online (Sandbox Code Playgroud)

Joa*_*son 5

DexieJS的AND运算符实现为过滤器函数或复合索引。实现查询的简单方法是使用filter方法,例如:

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

这意味着第一个过滤器将针对IndexedDB运行,并且附加条件将针对DexieJS的每个找到的项目运行,这可能满足您的需求,也可能不够。

关于如何使用复合索引,在没有所需集合和确切查询的更多详细信息的情况下,将其应用于您的确切情况会有些困难,但是此处提供了更多信息