Check if IndexedDB objectStore already contains key

Chris picture Chris · Mar 9, 2013 · Viewed 15.1k times · Source

Adding an object to an IndexedDB objectStore will fail if the key already exists. How can I check for the existence of an object with a given key – preferably synchronously (no reason for another layer of callbacks) and without pulling the object.

I know how to do get requests asynchronously via transactions, but it seems a bit of an ordeal to go through every time I want to add an object.

note Solution only has to work in Chrome (if that helps)

Answer

Kyaw Tun picture Kyaw Tun · Mar 10, 2013

The best way to check existence of a key is objectStore.count(key). Which is async.

In your case, the best option is openCursor of your key. If exists, cursor will come up.

var req = objectStore.openCursor(key);
req.onsuccess = function(e) {
  var cursor = e.target.result; 
  if (cursor) { // key already exist
     cursor.update(obj);
  } else { // key not exist
     objectStore.add(obj)
  }
};