Course contentsShow
← Web Development
Lesson 792 of 2,98214. Browser StorageFree lesson

Cursors for Iterating Records

Use openCursor() to iterate through multiple records efficiently with filtering options.

Cursors for Iterating Records

What you'll learn: How to loop through multiple IndexedDB records efficiently using cursors with filtering capabilities.

When you need to process many records from an IndexedDB object store—not just retrieve one by key—you'll use a cursor. Think of a cursor like a reading finger moving line-by-line through a book: it points to one record at a time, lets you examine or modify it, then moves to the next.

Why Use Cursors?

Retrieving records one-by-one by key works, but what if you want to display all users, find all items over a certain price, or update multiple records? Cursors let you iterate through results without loading everything into memory at once.

The openCursor() Method

You create a cursor by calling openCursor() on an object store or index within a transaction:

const transaction = db.transaction(['products'], 'readonly');
const store = transaction.objectStore('products');
const request = store.openCursor();

request.onsuccess = (event) => {
  const cursor = event.target.result;
  if (cursor) {
    console.log('Key:', cursor.key);
    console.log('Value:', cursor.value);
    cursor.continue(); // Move to next record
  } else {
    console.log('All records processed');
  }
};

How It Works

  • cursor.value gives you the current record
  • cursor.key gives you the current key
  • cursor.continue() moves to the next record
  • When cursor is null, you've reached the end

Filtering with Range Options

You can pass an IDBKeyRange to openCursor() to filter which records you iterate:

const range = IDBKeyRange.bound(10, 50);
store.openCursor(range); // Only iterate records with keys 10-50

Key Takeaway: Use openCursor() to efficiently walk through multiple IndexedDB records one at a time, with optional filtering through key ranges.