Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

IndexedDB: create an index, add, count, and read records

Create a secondary index, insert records without overwriting them, and query by either primary key or index key.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

store.createIndex(name, keyPath)
store.createIndex(name, keyPath, options)
store.count()
store.count(query)
store.add(value)
store.add(value, key)
store.getAll()
store.getAll(query)
store.getAll(query, count)
store.getAll(options)
store.index(name)

IDBObjectStore.createIndex/count/add/getAll/index groups five methods on a transaction-bound object store. Each record has a primary key and a value. IndexedDB is a web platform API, not part of ECMAScript, and database access follows the same-origin policy.

createIndex(name, keyPath, options) returns an IDBIndex immediately but can only run in an active versionchange transaction, typically in upgradeneeded. The key path tells IndexedDB where to extract the index key; it does not add a field to the record. unique: true disallows duplicate index keys; multiEntry: true indexes valid array elements separately. Both default to false. You cannot combine multiEntry: true with a compound key path supplied as an array of paths.

add(value, key) stores a structured clone and gives the new record's key in request.result. Omit the second argument for a store with an in-line key; supply it for an out-of-line store without a key generator. A duplicate primary key or unique-index violation fails the request with ConstraintError. Use put() to insert or replace by primary key instead.

count(query) gives a number, whereas getAll(query, count) gives an array of cloned values, empty when nothing matches. Both accept a primary key or IDBKeyRange. If you omit the query, every record in the store is eligible. A positive count limits how many values getAll() returns. The default order is ascending primary key. The newer getAll({ query, count, direction }) form supports directions such as "prev"; check target browser support.

index(name) immediately returns an existing IDBIndex tied to the same transaction. An unknown name throws NotFoundError; names are case-sensitive. store.getAll("sci-fi") matches a primary key, while store.index("byGenre").getAll("sci-fi") returns record values matched by index key.

add(), count(), and getAll() return an IDBRequest, not a Promise. Read result after success and handle error. In an ordinary transaction, writes require readwrite. Queue requests while the transaction is active: waiting for unrelated asynchronous work can let it finish. Request success is not a commit; wait for the transaction's complete event to confirm it.

Examples

<!doctype html>
<meta charset="utf-8">
<title>IndexedDB object store methods</title>
<script>
(() => {
  const dbName = `cktis-books-${crypto.randomUUID()}`;
  const open = indexedDB.open(dbName, 1);

  open.onupgradeneeded = () => {
    const store = open.result.createObjectStore('books', { keyPath: 'id' });
    store.createIndex('byGenre', 'genre');
  };
  open.onerror = () => console.error(open.error);

  open.onsuccess = () => {
    const db = open.result;
    const tx = db.transaction('books', 'readwrite');
    const store = tx.objectStore('books');

    const cleanup = () => {
      db.close();
      const deletion = indexedDB.deleteDatabase(dbName);
      deletion.onerror = () => console.error(deletion.error);
    };
    tx.onabort = () => {
      console.error(tx.error);
      cleanup();
    };

    const added = store.add({ id: 3, title: 'Orbit', genre: 'sci-fi' });
    store.add({ id: 1, title: 'Dunes', genre: 'sci-fi' });
    store.add({ id: 2, title: 'Herbs', genre: 'guide' });
    const total = store.count();
    const all = store.getAll();
    const matches = store.index('byGenre').getAll('sci-fi');

    tx.oncomplete = () => {
      const titles = (request) => request.result.map((book) => book.title).join(', ');
      console.log(`Added key: ${added.result}`);
      console.log(`Total: ${total.result}`);
      console.log(`All: ${titles(all)}`);
      console.log(`Sci-fi: ${titles(matches)}`);
      cleanup();
    };
  };
})();
</script>

Result

Added key: 3
Total: 3
All: Dunes, Herbs, Orbit
Sci-fi: Dunes, Orbit

Serve this HTML over HTTPS, open it in a browser, and check the developer console. The example creates a separate temporary database and deletes it afterward. It inserts three books out of primary-key order, then logs all titles by `id` and the titles selected by the genre index after the transaction commits.

Related lessons

  • JavaScript · Lesson 21 · Intermediate · Version: 3

Sources