Search code examples
javascriptindexingindexeddbdexie

Update Dexie entry if unique key exists


I set up a table with a unique key like:

let db = new Dexie("myDB");
db.version(1).stores({
  myTable : "++id,&label"
});
db.put({label:"A",name:"Bob"});

I want to insert a new object with the label "A". But I get a ConstraintError because label "A" already exists.

db.put({label:"A",name:"Mark"});

In MySQL I would do something like:

INSERT INTO myTable (label, name) VALUES ("A", "Mark") ON DUPLICATE KEY UPDATE SET label=VALUES(label), name=VALUES(name)

Can I do something similar with IndexedDB using Dexie? Keep in mind there might be multiple unique indexes, so simply searching for index "A" to see if it exists might not be a viable option.


Solution

  • No, there is no functionality like that in indexedDB, and therefore I assume there is also nothing in dexie which is basically just a wrapper library.

    indexedDB will just fail with a constraint error every time you try to store an object.

    You need to use openCursor or get or openKeyCursor to find if a record exists, and then decide whether to use put. This will always involve two requests, even if you use openCursor and cursor.update, as cursor.update is just syntactic sugar for put.

    Alternatively, I suppose you could just shift your perspective, and say that various puts may fail. Or restructure your object store and constraints. This particular type of issue is definitely a criterion in deciding how to store objects.