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

Creating Object Stores

Define object stores during upgrades with keyPath and autoIncrement options for data organization.

Creating Object Stores

You'll learn how to define object stores during database upgrades to organize your IndexedDB data with automatic key generation and custom key paths.

What is an Object Store?

An object store is like a single table in a traditional database—it's where you actually store your data in IndexedDB. Just as a database can have multiple tables (users, products, orders), an IndexedDB database can have multiple object stores, each holding a different type of data.

Creating Object Stores in onupgradeneeded

You can only create object stores during the onupgradeneeded event—when the database version changes. This is IndexedDB's way of managing schema changes safely.

const request = indexedDB.open('MyDatabase', 1);

request.onupgradeneeded = function(event) {
  const db = event.target.result;
  
  // Create a simple object store
  const store = db.createObjectStore('users');
};

Key Configuration Options

Using keyPath

The keyPath option tells IndexedDB which property of your objects should be used as the unique key:

const store = db.createObjectStore('users', { keyPath: 'email' });
// Now each user object must have an 'email' property

Using autoIncrement

When you want IndexedDB to automatically generate sequential numeric keys:

const store = db.createObjectStore('tasks', { autoIncrement: true });
// Keys will be 1, 2, 3, 4...

Combining Both

const store = db.createObjectStore('products', { 
  keyPath: 'id', 
  autoIncrement: true 
});
// Objects will get an auto-generated 'id' property

Key Takeaway: Object stores are created during onupgradeneeded using createObjectStore(), with keyPath defining which property identifies each record and autoIncrement enabling automatic key generation for organizing your data.