uberlaufer uberlaufer - 4 months ago 13
Javascript Question

What's the difference between key and primaryKey in IDBCursor of IndexedDB

The documentation here says that


Returns the cursor's current key. (Cursors also have a key and a value which represent the key and the value of the last iterated record.)


Returns the cursor's current effective key. (If the source of a cursor is an object store, the effective object store of the cursor is that object store and the effective key of the cursor is the cursor's position.)

In the examples below however the two are used exactly the same and I get the same values for both:

So what is the practical difference?


If you're iterating over an object store, they are the same.

If you are iterating over an index, the key is the index key and the primaryKey is the key in the object store.

For example:

 book_store = db.createObjectStore('books');
 title_index = store.createIndex('by_title', 'title');

 key = 123;
 value = {title: 'IDB for Dummies', author: 'Alice'};
 book_store.put(value, key);

 book_store.openCursor().onsuccess = function(e) {
   cursor = e.target.result;
   console.log(cursor.key); // logs 123
   console.log(cursor.primaryKey); // logs 123
 title_index.openCursor().onsuccess = function(e) {
   cursor = e.target.result;
   console.log(cursor.key); // logs 'IDB for Newbies'
   console.log(cursor.primaryKey); // logs 123