CodeBlanks Logo Icon CodeBlanks

Creating an object store

JavaScript course · Advanced · Lesson 86/100

Learn to create an object store in a database and the keyPath.

Object store and keyPath

In IndexedDB, data lives in collections called object stores. Each store finds records by a key; the keyPath property tells which field of the record is the key.

const store = db.createObjectStore('notes', { keyPath: 'id' });

Here 'notes' is the store name and { keyPath: 'id' } says the id field of each record is the key. Creating an object store is only allowed inside onupgradeneeded.

onupgradeneeded and event.target.result

The onupgradeneeded listener receives an event. event.target.result is the IDBDatabase instance whose version is being bumped; you call createObjectStore and createIndex on it.

request.onupgradeneeded = function(event) {
  const db = event.target.result;
  db.createObjectStore('notes', { keyPath: 'id' });
};

This event runs exactly once, when the version changes. That is why all structure creation goes here.

Exercise Create the notes store

Assign a function to request.onupgradeneeded. Inside, read event.target.result into a db variable. Use db.createObjectStore to create a store named 'notes' with keyPath set to 'id'.

Show example solution
request.onupgradeneeded = function(event) {
  const db = event.target.result;
  db.createObjectStore('notes', { keyPath: 'id' });
};

Test yourself

  1. Create an object store

    const store = db.____('notes', { keyPath: 'id' });
    Show answer
    const store = db.createObjectStore('notes', { keyPath: 'id' });
  2. What does keyPath do?

    • Adds files to the store
    • Returns the database version
    • Names which field of the record is the key
    • Creates an index
    Show answer

    Names which field of the record is the key — Correct! keyPath names the key field of the record.

  3. Match IndexedDB terms

    object store
    record collection
    keyPath
    key field
    createObjectStore
    store creation
    onupgradeneeded
    structure change

All lessons in Advanced