2015-01-05 2 views
0

Я переработал старый проект и внес некоторые улучшения, и я больше не могу понять, как загрузить одну запись из indexedDB. Я очистил БД и сделал новый импорт, и я вижу все записи (включая ту, которую я использую для entryID) в разделе «Ресурсы хромовых инспекторов». Я попытался вытащить всевозможные идентификационные номера, все, что я могу подтвердить, находятся в БД от инспектора, все они возвращаются не определены. Это код, который я использую.indexedDB objectStore.get() всегда возвращает undefined несмотря на результаты в DB

/* 
    This loads up a specific entry and fills in the #entry-details div with it's data. This div is placed overtop the search 
    content so that when it is closed the user remains exactly where they were and the search does not need to re-process. 
*/ 
function getEntryDetails(){ 

    var entryID = 193; // just for now, this will be grabbed from somewhere else later 

    // Where going to need a varible to store all this generated HTML in 
    var html = ''; 

    // First we need to load up the indexedDB and get the record in question. 
    var db = indexedDB.open('pediaCache'); 

    // lets get a couple of the errors out of the way. 
    db.onerror=function(e){html += 'There was an error loading the database.<br/>'+e;} 
    db.onblocked=function(e){html += 'Database access blocked.<br/>'+e;} 

    // Now for when things go the right way 
    db.onsuccess=function(e){ 
     var db = e.target.result; 

     // Get the requested entry 
     console.log('Attempting to load entry ID '+entryID); 
     var transaction = db.transaction(['entries'],'readonly'); 
     var objectStore = transaction.objectStore('entries'); 
     var entry = objectStore.get(entryID); 

     entry.onerror = function(e) { 
      console.log('error'); 
      console.log(e.target.result); 
      console.log(e); 
     }; 
     entry.onsuccess = function(e) { 
      console.log('success'); 
      console.log(e.target.result); 
      console.log(e); 
     }; 

    } 

} 

Это действительно только некоторые слегка измененный код из оригинальной версии (так как эта функция та же, я действительно только изменил имена баз данных и ObjectStore здесь и в импортера). Выполнение этого кода в Chrome (запускается вручную после того, как я знаю, что все другие функции, связанные с БД, выполняются) даже запускает «onsuccess» даже с неопределенным результатом (как если бы запись не была в БД, но снова я проверил ее в там).

В соответствии с просьбой, содержание console.dir (е):

{ 
    "path": { 
     "length": 0 
    }, 
    "cancelBubble": false, 
    "returnValue": true, 
    "srcElement": { 
     "readyState": "done", 
     "transaction": { 
      "onerror": null, 
      "oncomplete": null, 
      "onabort": null, 
      "error": null, 
      "db": { 
       "onversionchange": null, 
       "onerror": null, 
       "onclose": null, 
       "onabort": null, 
       "objectStoreNames": { 
        "0": "entries", 
        "length": 1 
       }, 
       "version": 3, 
       "name": "pediaCache" 
      }, 
      "mode": "readonly" 
     }, 
     "source": { 
      "autoIncrement": false, 
      "transaction": { 
       "onerror": null, 
       "oncomplete": null, 
       "onabort": null, 
       "error": null, 
       "db": { 
        "onversionchange": null, 
        "onerror": null, 
        "onclose": null, 
        "onabort": null, 
        "objectStoreNames": { 
         "0": "entries", 
         "length": 1 
        }, 
        "version": 3, 
        "name": "pediaCache" 
       }, 
       "mode": "readonly" 
      }, 
      "indexNames": { 
       "0": "title", 
       "length": 1 
      }, 
      "keyPath": null, 
      "name": "entries" 
     }, 
     "error": null 
    }, 
    "defaultPrevented": false, 
    "timeStamp": 1420434102528, 
    "cancelable": false, 
    "bubbles": false, 
    "eventPhase": 0, 
    "currentTarget": null, 
    "target": { 
     "readyState": "done", 
     "transaction": { 
      "onerror": null, 
      "oncomplete": null, 
      "onabort": null, 
      "error": null, 
      "db": { 
       "onversionchange": null, 
       "onerror": null, 
       "onclose": null, 
       "onabort": null, 
       "objectStoreNames": { 
        "0": "entries", 
        "length": 1 
       }, 
       "version": 3, 
       "name": "pediaCache" 
      }, 
      "mode": "readonly" 
     }, 
     "source": { 
      "autoIncrement": false, 
      "transaction": { 
       "onerror": null, 
       "oncomplete": null, 
       "onabort": null, 
       "error": null, 
       "db": { 
        "onversionchange": null, 
        "onerror": null, 
        "onclose": null, 
        "onabort": null, 
        "objectStoreNames": { 
         "0": "entries", 
         "length": 1 
        }, 
        "version": 3, 
        "name": "pediaCache" 
       }, 
       "mode": "readonly" 
      }, 
      "indexNames": { 
       "0": "title", 
       "length": 1 
      }, 
      "keyPath": null, 
      "name": "entries" 
     }, 
     "error": null 
    }, 
    "type": "success" 
} 

и создание на ObjectStore (onupgradeneeded).

// We need to be able to update the db schema (or create it for that matter) 
    db.onupgradeneeded=function(e){ 
     var db = e.target.result; 

     // In the future some of theme might want to get commented out... 
     postMessage({'status':'importing','message':'Upgrading local database.'}); 
     // Check if the table is in there, if it's not then create it 
     console.log(db.objectStoreNames); 
     if(db.objectStoreNames.contains('entries')==false){ 
      var db = db.createObjectStore('entries'); 

      // Create the indexes so we can more easily search and sort and stuff (just one, we sort by name, everything else done by magic) 
      db.createIndex('title' ,'ZTITLE' ,{unique:false}); 

     } 

    }; 
+0

Измените console.log (e) на console.dir (e) и скопируйте и вставьте результаты здесь. – Josh

+0

Я обновлю вопрос с результатами. –

+0

Какие аргументы вы передаете createObjectStore? Скопируйте и вставьте соответствующее заявление из своей функции onupgradedededed. Просто догадаться, но разве вы не используете keyPath? – Josh

ответ

7

Нашли проблему, надеюсь, никто не сделать то же простую ошибку я сделал, но в случае, если кто-то и проходит через этот вопрос вот в чем проблема.

Ключ, который я добавлял в базу данных, был строкой. Ключ, который я запрашивал, был int.

Не будьте похожими на меня, проверьте свои типы данных.

+0

@PhillipGoch спасибо! решил мою проблему. – Gagan

Смежные вопросы