javascript - Indexeddb 在同一索引上搜索多个值

标签 javascript html indexeddb

我在 IndexedDB 数据库中记录 JSON 流,但无法对同一索引上的多个值进行相等性搜索。

我的数据:

datas = [
  {name : 'Test P1', location : 'P1'},
  {name : 'Test P1', location : 'P1'},
  {name : 'Test P2', location : 'P2'},
  {name : 'Test P2', location : 'P2'},
  {name : 'Test P3', location : 'P3'},
  {name : 'Test P3', location : 'P3'},
  {name : 'Test P3', location : 'P3'}
]

数据库 build 及要求:

// In onupgradeneeded
var objectStore = db.createObjectStore('entreprises', {keyPath: 'id_loc'});
objectStore.createIndex("name", "name");
objectStore.createIndex("location", "location");


//In query section
var transaction = db.transaction('entreprises','readonly');
var store = transaction.objectStore('entreprises');
var index = store.index('location');
// I want select only records where location = P1 and location = P2
var request = index.openCursor(IDBKeyRange.only(['P1', 'P2']));
// Select the first matching record
var request = index.get(IDBKeyRange.only(['P1', 'P2']));

查询找到我的任何记录。可以这样做吗?谢谢。

最佳答案

我怀疑是否可以使用 only() 数组,API 也没有这么说,请检查下面的 IDBKeyRange.only() .
可能这就是它不适合您的原因。

The only() method of the IDBKeyRange interface creates a new key range containing a single value.

因此,您可以做的是打开“P1”或“P2”(以行数较少者为准)的游标,然后循环游标以检查它是否包含其他所需值。下面是我为您方便引用而创建的示例,因此请对其进行调整以进行更改,例如删除“位置”、“P1”、“P2”等硬编码值。

var resultArr = [];
var keyRange = IDBKeyRange.only("P1");
cursorHandler = indexHandler.openCursor(keyRange);

cursorHandler.onerror = function(event) {
    if (errorCallBack && typeof(errorCallBack) == 'function') {
        errorCallBack(event);
    }
};

cursorHandler.onsuccess = function(event) {
    var cursor = event.target.result;
    if (cursor) {
        if(cursor.value != null && cursor.value != undefined){
            if(cursor.value["location"] == "P2"){
                resultArr.push(cursor.value);
            }
         }
        cursor["continue"]();
    } else{
        var resultObj = {"rows" : resultArr};
        if (successCallBack && typeof(successCallBack) == 'function') {
            successCallBack(resultObj);
        }
    }
    return;
};

关于javascript - Indexeddb 在同一索引上搜索多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30737219/

相关文章:

javascript - Google Data Studio 自定义图表

javascript - 使用 jquery 更改视口(viewport)元标记

javascript - 重复命名事务和对象存储

javascript - 在同一域的两个不同离线 Web 应用程序中创建/访问 indexedDB 使用相同的数据库

javascript - 使用带有事件处理程序的 Javascript、Jquery 时,怎么会知道 'event is event' ?

javascript - 倒计时完成后立即重定向

javascript - 隐藏div中的日历

html - 定位相对元素,距顶部与左侧的距离相同

javascript - 允许 iframe 成为全屏、跨浏览器

html - 如何从 indexedDB 获取对象库?