Search⌘ K

Creating an Object Store

Explore how to create object stores in IndexedDB with JavaScript, including using the createObjectStore() method and managing keyPath and autoIncrement options. Understand versioning to update object stores properly and handle multiple database versions, helping you organize data effectively in your web applications.

The createObjectStore() method

To create an object store, we can use the createObjectStore() method.

Syntax

createObjectStore(name);
createObjectStore(name, options);

The createObjectStore method can take two arguments:

  • name: This is the name for the new object store to be created.

  • options: The options object can contain the keyPath(primaryKey) and autoIncrement attributes. It’s an optional argument.

    • keyPath (optional): This specifies the name of the property that will be used as the key for the objects in the object store. If this property is omitted, a unique key is generated for each object automatically.

    • autoIncrement (optional): This property is a boolean value that specifies whether the object store should automatically generate a new key value for each new object that’s added to the store.

The keyPath vs. autoIncrement attributes

  • autoIncrement: For data that can’t be differentiated based on a specific property, we can set the autoIncrement as true.

  • keyPath: This attribute is used to define data that can be differentiated based on a specific property. For example, if we’re going to store the student’s details in the object store, then the student id ...