AKA
AKA

Reputation: 318

Searching for non-existent key in IndexedDB objectStore still returns as success

I'm trying to see whether an entry already exists in an objectStore. If the entry exists, I need to alter a few of its fields; if the entry does not exist, I need to add it.

Here's my query:

var db = html5rocks.indexedDB.db;
  var trans = db.transaction(["topics"], "readwrite");
  var store = trans.objectStore("topics");
  var findRequest = store.get(tHash);
findRequest.onsuccess = function(event){
  console.log("logging event");
  console.log(event);
  var cursor = event.target.result;
}
findRequest.onerror(e){
console.log(e);
}

The issue I'm experiencing is that the findRequest.onsuccess function always fires - even though it's impossible that the get(tHash) request is finding anything (By the way, the "topics" objectStore contains zero entries when I do this...). I figured I'd use the onsuccess and onerror functions to tell if I needed to update an existing record or create a new one. What am I doing wrong?

Upvotes: 0

Views: 936

Answers (1)

Nik Haldimann
Nik Haldimann

Reputation: 2011

Directly from the horse's mouth:

IDBObjectStore.get() produces the same result if a record with the given key doesn't exist as when a record exists, but has undefined as value. If you need to tell the two situations apart, you can use openCursor with the same key. This will return a cursor with undefined as value if a record exists, or no cursor if no such record exists.

I think you want something like:

var cursorRequest = store.openCursor(tHash);
cursorRequest.onsuccess = function(event) {
  var cursor = event.result;
  if (cursor) {
    // entry exists
  } else {
    // entry doesn't exist
  }
}    

Upvotes: 5

Related Questions