IndexedDB: retrieve the out-of-line key associated with a particular object in an object store

1k views Asked by At

Say I have an object store, which was created like this:

IDBDatabase.createObjectStore(Name, {autoIncrement: true });

Now, say I retrieve an object from that object store using an index to look it up.

Is there a way that I can retrieve the out-of-line key associated with the object so I can modify/delete it with IDBObjectstore.put() / IDBObjectstore.delete(), or am I stuck iterating over the object store with a cursor (comparing based on some arbitrary property) and using cursor.update() / cursor.delete()?

Initially I would think not, because the point of having specific keys is that two identical objects might reside in the object store, so the browser can't know what object to give you when its provided with only the object itself. Presumably though, since I retrieved it with an index in the first place, there may be some way to utilize the index to retrieve the out-of-line key that's associated with the object I am working with.

2

There are 2 answers

0
hagrawal7777 On BEST ANSWER

When data is inserted into datastore then the event object returned contains the information about the key used for inserting data. It can be retrieved using event.target.result. You can collect the information at that time.

Whether in-line-keys or out-of-line keys, you can get it same way.

var transaction = DB_HANDLER.transaction([tableName], "readwrite");
var objectStore = transaction.objectStore(tableName);
var request = objectStore.add(data);

request.onsuccess = function(event) {
    console.log("Key used for inserting data = " + event.target.result);
};
1
Kyaw Tun On

You have to keep the out-of-line key generated when you put. It is in the success request event result.