Skip to content

Connecting to Database & Creating Object Store

prasenjeet-symon edited this page Sep 12, 2020 · 1 revision

Connect to the database

Well opening the database connection is pretty straight forward use just import the openDB and call that.

import { openDB } from 'indexed-pdb'

(
    async function () {
        const database = openDB('test_database', 1, function (upgradeDB) {
            // before creating new object store check if already created
            // our table name is test_table
            if (!(upgradeDB.objectStoreNames.contains('test_table'))) {
                upgradeDB.createObjectStore('test_table')
            }
        })
    }
)()

KeyPath and AutoIncrement

While creating the object store you do have the option to create the primary key. You can create the primary key in the following way

upgradeDB.createObjectStore('test_table', {keyPath :'id', autoIncrement: true})

The above statement will create the object store ( table ) in the database 'test_database' with a primary key set to the 'id' property of the object and also 'autoIncrement' feature is turned on by setting the 'autoIncrement' property to true.

For the test_table indexed-pdb will automatically create the primary key and auto-increment it whenever new data will be inserted to this object-store.

If the autoIncrement feature is turned off then you must have to provide the unique value to the id property of the object while inserting the data to object-store 'test_table'

Clone this wiki locally