Reputation: 191
Originally I'd written this piece of code to search for a 'section' object using its key:
var section = {};
var getSection = store.get(id);
getSection.onsuccess = function(e){
section = e.target.result;
}
But it was unable to find the object (section was "undefined") even though by inspection through the browser the object with the corresponding key clearly exists. Furthermore, the following code does work:
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();
}
}
It produces the same result, but the latter is much slower. I'd like the first way to work. Why isn't it?
For reference, here is my objectStore definition for "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});
Upvotes: 0
Views: 313
Reputation: 18690
You could try using store.index('section_id').get(id);
instead of store.get(id);
as a quick fix. Given that your keypath is defined to point to section_id, it seems strange because I also would expect get to work.
A second issue might be a data type conflict. Are you mixing strings and numbers? Are you storing strings then querying by number, or something like that? Because your cursor example uses ==
which is type-insensitive. To test this quickly, try your cursor test using ===
and see if it still works. If it fails, you most likely are doing something like storing ids as strings and then querying with numerical id.
Upvotes: 1
Reputation: 4180
if it is undefined, it is because no value is found. How is your objectstore configured? what did you define as key? I think this will be te issue.
Upvotes: 0