IDBCursor

This article is in need of a technical review.

« IDBCursor

The IDBCursor interface of the IndexedDB API represents a cursor for traversing or iterating over multiple records in a database.

The cursor has a source that indicates which index or object store it is iterating. It has a position within the range, and moves in a direction that is increasing or decreasing in the order of record keys. The cursor enables an application to asynchronously process all the records in the cursor's range.

You can have an unlimited number of cursors at the same time. You always get the same IDBCursor object representing a given cursor. Operations are performed on the underlying index or object store.

Methods

IDBCursor.advance
Sets the number times a cursor should move its position forward.
IDBCursor.continue
Advances the cursor to the next position along its direction, to the item whose key matches the optional key parameter.
IDBCursor.delete
Returns an IDBRequest object, and, in a separate thread, deletes the record at the cursor's position, without changing the cursor's position.
IDBCursor.update
Returns an IDBRequest object, and, in a separate thread, updates the value at the current position of the cursor in the object store.

Properties

IDBCursor.source Read only
On getting, this object returns the IDBObjectStore or IDBIndex that the cursor is iterating. This function never returns null or throws an exception, even if the cursor is currently being iterated, has iterated past its end, or its transaction is not active.
IDBCursor.direction Read only
Is a DOMString that, on getting, returns the direction of traversal of the cursor. See Constants for possible values.
IDBCursor.key Read only
Returns the key for the record at the cursor's position. If the cursor is outside its range, this is set to undefined. The cursor's key can be any data type.
IDBCursor.primaryKey Read only
Returns the cursor's current effective key. If the cursor is currently being iterated or has iterated outside its range, this is set to undefined. The cursor's primary key can be any data type.

Constants

Obsolete since Gecko 25 (Firefox 25 / Thunderbird 25 / SeaMonkey 2.22)
This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it.

These constants are no longer available. You should use directly the string constants instead. (bug 891944)

  • NEXT : "next" : The cursor shows all records, including duplicates. It starts at the lower bound of the key range and moves upwards (monotonically increasing in the order of keys).
  • NEXTUNIQUE : "nextunique" : The cursor shows all records, excluding duplicates. If multiple records exist with the same key, only the first one iterated is retrieved. It starts at the lower bound of the key range and moves upwards.
  • PREV : "prev" : The cursor shows all records, including duplicates. It starts at the upper bound of the key range and moves downwards (monotonically decreasing in the order of keys).
  • PREVUNIQUE : "prevunique" : The cursor shows all records, excluding duplicates. If multiple records exist with the same key, only the first one iterated is retrieved. It starts at the upper bound of the key range and moves downwards.

Example

In the following code snippet, we open a transaction and manipulate a data set using a cursor. You can see that the cursor allows us to create a special if ... else structure, which runs while the cursor still has data inside it to iterate through (if(cursor)). Also, the cursor does not require us to select the data based on any key; we can just grab all of it. Also note that in each iteration of the loop, you can grab values from the current cursor object using cursor.value.foo.

// Open our object store and then get a cursor list of all the different data items in the IDB to iterate through
    var objectStore = db.transaction('toDoList').objectStore('toDoList');
    objectStore.openCursor().onsuccess = function(event) {
      var cursor = event.target.result;
        // if there is still another cursor to go, keep runing this code
        if(cursor) {
          // create a list item to put each data item inside when displaying it
          var listItem = document.createElement('li');
          
          // check which suffix the deadline day of the month needs
          if(cursor.value.day == 1 || cursor.value.day == 21 || cursor.value.day == 31) {
            daySuffix = "st";
          } else if(cursor.value.day == 2 || cursor.value.day == 22) {
            daySuffix = "nd";
          } else if(cursor.value.day == 3 || cursor.value.day == 23) {
            daySuffix = "rd";
          } else {
            daySuffix = "th";  
          }
          
          // build the to-do list entry and put it into the list item via innerHTML.
          listItem.innerHTML = cursor.value.taskTitle + ' — ' + cursor.value.hours + ':' + cursor.value.minutes + ', ' + cursor.value.month + ' ' + cursor.value.day + daySuffix + ' ' + cursor.value.year + '.';
          
          if(cursor.value.notified == "yes") {
            listItem.style.textDecoration = "line-through";
            listItem.style.color = "rgba(255,0,0,0.5)";
          }

          // put the item item inside the task list
          taskList.appendChild(listItem);  
          
          // create a delete button inside each list item, giving it an event handler so that it runs the deleteButton()
          // function when clicked
          var deleteButton = document.createElement('button');
          listItem.appendChild(deleteButton);
          deleteButton.innerHTML = 'X';
          // here we are setting a data attribute on our delete button to say what task we want deleted if it is clicked!
          deleteButton.setAttribute('data-task', cursor.value.taskTitle);
          deleteButton.onclick = function(event) {
            deleteItem(event);
          }
          
          // continue on to the next item in the cursor
          cursor.continue();
        
        // if there are no more cursor items to iterate through, say so, and exit the function
        } else {
          note.innerHTML += '<li>Entries all displayed.</li>';
        }
      }
    }

Specifications

Specification Status Comment
Indexed Database API Candidate Recommendation  

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support 12webkit
23
4.0 (2.0) 10 17 Not supported
Feature Android Firefox Mobile (Gecko) Firefox OS IE Phone Opera Mobile Safari Mobile
Basic support 4.4 6.0 (6.0) 1.0.1 10 17 Not supported

Be careful in Chrome as it still implements the old specification along the new one. Similarly it still has the prefixed webkitIndexedDB property even if the unprefixed indexedDB is present.

See also

To learn more about various topics, see the following

  • Starting transactions: IDBDatabase
  • Setting transaction modes: IDBTransaction
  • Setting a range of keys: IDBKeyRange
  • The reference application for the examples in this reference: To-do Notifications (view example live.) Not every snippet appears in this example, but every example uses the same data structure and syntax, and they will make sense in the context of this example.