AI Workshop: learn to build apps with AI →
IndexedDB: Migrations

Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.


Migrate from previous version of a database

The third (optional) parameter of the openDB() function is an object that can contain an upgrade function called only if the version number is higher than the currently installed database version. In that function body you can upgrade the structure (stores and indexes) of the db:

const name = 'mydbname'
const version = 1
openDB(name, version, {
  upgrade(db, oldVersion, newVersion, transaction) {
    console.log(oldVersion)
  }
})

In this callback, you can check which version the user is upgrading from and perform the appropriate operations.

You can perform a migration from a previous database version using this pattern:

(async () => {
  //...
  const dbName = 'mydbname'
  const storeName = 'store0'
  const version = 1

  const db = await openDB(dbName, version, {
    upgrade(db, oldVersion, newVersion, transaction) {
      switch (oldVersion) {
        case 0: // no db created before
          // a store introduced in version 1
          db.createObjectStore('store1')
        case 1:
          // a new store in version 2
          db.createObjectStore('store2', { keyPath: 'name' })
      }
      db.createObjectStore(storeName)
    }
  })
})()

Lessons in this unit:

0: Introduction
1: Loading the idb library
2: Creating a database and a store
3: Adding data into a store
4: Retrieving data from a store
5: Deleting data
6: ▶︎ Migrations
7: Unique keys