Check if IndexedDB objectStore already contains key

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)
  }
};

The question is why do you want to know this? Maybe you should use another approach?

You can use auto increment, this way you don't need to check if a key exists, you will always get a unique one.

You can also use the put method instead of the add method. With the put the data will be updated if the key exists and if the key doesn't exist the data is added.

Everything depends on the reason why you want to check if something exists.


So far none of the browsers have the sync API implemented so you're going to have to do it async. An objectStore exposes a get method which you provide it with a key and it'll return you the object (or null) that matches the key.

There's a really good tutorial on MDN that covers using IDB, and getting a record is covered too, but the inlined code is:

db.transaction("customers").objectStore("customers").get("444-44-4444").onsuccess = function(event) {
  alert("Name for SSN 444-44-4444 is " + event.target.result.name);
};

If you don't want retrieve the record then you can always used the count method on an index as explained here in the spec. Based on the result of that you can either use add or put to modify the record, it'll save extracting the record if you don't need to.


A bit late for an answer, but possible it helps others. I still stumbled -as i guess- over the same problem, but it's very simple:

If you want to INSERT or UPDATE records you use objectStore.put(object) (help)
If you only want to INSERT records you use objectStore.add(object) (help)

So if you use add(object), and a record key still exists in DB, it will not overwritten and fires error 0 "ConstraintError: Key already exists in the object store".

If you use put(object), it will be overwritten.