Google News
logo
JavaScript IndexedDB - Interview Questions
How do you create an object store in IndexedDB?
To create an object store in IndexedDB, you typically perform this operation within the onupgradeneeded event handler of the indexedDB.open() method. Here's how you can create an object store:
// Step 1: Open or create a database
var request = indexedDB.open("myDatabase", 1);

// Step 2: Handle the database events
request.onerror = function(event) {
    // Handle errors
    console.log("Error opening database");
};

request.onsuccess = function(event) {
    // Get reference to the opened database
    var db = event.target.result;
    console.log("Database opened successfully");
    
    // Further database operations can be performed here
};

// Step 3: Define the database structure in case of upgrade
request.onupgradeneeded = function(event) {
    // Get reference to the opened database
    var db = event.target.result;

    // Create an object store (table) to store data
    var objectStore = db.createObjectStore("myObjectStore", { keyPath: "id" });

    // Define indexes if needed
    objectStore.createIndex("name", "name", { unique: false });
    objectStore.createIndex("email", "email", { unique: true });
};?

Explanation :

Open or create a database using indexedDB.open("myDatabase", 1). The first parameter is the name of the database, and the second parameter is the version number. If the database doesn't exist, it will be created. If it does exist and the version number is greater than the existing version, the onupgradeneeded event will be triggered.

Handle database events such as error and success. In case of an error, you can handle it within the request.onerror event handler. In case of success, you can further perform database operations within the request.onsuccess event handler.

Define the database structure within the onupgradeneeded event handler. This is where you create object stores and define their structure. In this example, we create an object store named "myObjectStore" with a key path of "id". We also define two indexes named "name" and "email" on the "name" and "email" properties of the stored objects, respectively.

Once the onupgradeneeded event handler is executed, the object store "myObjectStore" will be created with the specified key path and indexes within the database. You can then use this object store to store and retrieve data within your IndexedDB database.
Advertisement