可以使用游标找到IndexedDB对象,但不能通过get(key)

时间:2015-11-15 02:52:44

标签: javascript jquery html indexeddb

最初我写这段代码来搜索“'部分'对象使用其键:

var section = {};
var getSection = store.get(id);
getSection.onsuccess = function(e){
    section = e.target.result;
}

但它无法找到对象(部分是"未定义"),即使通过浏览器检查显然存在具有相应键的对象。此外,以下代码可以正常工作:

var section = {};
var transaction = db.transaction(['section'], 'readonly');
var store = transaction.objectStore('section');
var index = store.index("section_id");
index.openCursor().onsuccess = function(e){
    var cursor = e.target.result;
    if (cursor){
        if (cursor.value['section_id'] == id){
            section = cursor.value;
        }
        cursor.continue();
    }
}

它产生相同的结果,但后者慢得多。我喜欢第一种工作方式。为什么不呢?

作为参考,这是我的objectStore定义" section":

        if (!thisdb.objectStoreNames.contains("section")){
            var objectStore = thisdb.createObjectStore("section", {keyPath:"section_id"});
            // Add properties
            objectStore.createIndex("section_id", "section_id", {unique:true});
            objectStore.createIndex("catalog_num", "catalog_num", {unique:false});
            objectStore.createIndex("title", "title", {unique:false});
            objectStore.createIndex("dow", "dow", {unique:false});
            objectStore.createIndex("meeting_days", "dow", {unique:false});
            objectStore.createIndex("start_time", "start_time", {unique:false});
            objectStore.createIndex("end_time", "end_time", {unique:false});
            objectStore.createIndex("instructor", "instructor", {unique:false});
            objectStore.createIndex("section", "section", {unique:false});
            objectStore.createIndex("room", "room", {unique:false});
            objectStore.createIndex("overview", "overview", {unique:false});
            objectStore.createIndex("requirements", "requirements", {unique:false});
            objectStore.createIndex("univ_num", "univ_num", {unique:false});
            objectStore.createIndex("term_id", "term_id", {unique:false});
            objectStore.createIndex("course_symbol", "course_symbol", {unique:false});

2 个答案:

答案 0 :(得分:1)

您可以尝试使用$ xcode-select libxml2 install代替store.index('section_id').get(id);作为快速修复。鉴于你的keypath被定义为指向section_id,这看起来很奇怪,因为我也希望能够工作。

第二个问题可能是数据类型冲突。你在混合字符串和数字吗?您是否存储字符串然后按数字查询,或类似的东西?因为您的游标示例使用了store.get(id);,它对类型不敏感。要快速测试,请使用==尝试光标测试,看看它是否仍然有效。如果它失败了,你很可能正在做一些事情,比如将id作为字符串存储然后用数字id查询。

答案 1 :(得分:0)

如果未定义,则是因为没有找到值。你的对象库是如何配置的?你把什么定义为关键?我认为这将是一个问题。