Google News
logo
JavaScript IndexedDB - Interview Questions
What are the two basic methods for upgrading an IndexedDB version?
There are two main approaches to perform a database version upgrade.

We can implement per-version upgrade functions: from 1 to 2, from 2 to 3, from 3 to 4, and onwards. Then, in upgradeneeded we can compare versions (e.g., old 2, now 4) and run per-version upgrades step by step, for every intermediate version (2 to 3, then 3 to 4).

Or we can examine the database : retrieve a list of existing object stores as db.objectStoreNames. The object is a DOMStringList that provides contains(name) method to check for the existence of the objects, and then we execute updates depending on what exists and what does not.

For small databases, the second variant may be simpler.

Code Example : Second Approach
let openRequest = indexedDB.open('db', 2);

// create/upgrade the database without version checks
openRequest.onupgradeneeded = function () {
  let db = openRequest.result;
  if (!db.objectStoreNames.contains('books')) {
    // if there's no "books" store
    db.createObjectStore('books', { keyPath: 'id' }); // create it
  }
};?
Advertisement