Skip to content

Manipulating single records

Martin Jurča edited this page Aug 14, 2015 · 7 revisions

Indexed-db.es6 provides simple methods for manipulating single records. The methods are based on the native IndexedDB API.

The database variable in all code examples is an opened database connection created using the DBFactory.open(...) method as described in the Defining database schema page.

Note that the methods described here return PromiseSync instances (as all methods for operations within a transaction do), not instances of the native Promise API, due to the limitations of the native IndexedDB API.

Fetching records

Single records can be fetched using the get() method:

let objectStore = database.getObjectStore("fooBar")
objectStore.get(primaryKeyOrKeyRange).then((record) => {
  // do something with the record
  // the record is undefined if the record does not exist
}).catch((error) => {
  // something went wrong
})

When a key range is used, the method resolves to the first record matching the range.

Since it is impossible to tell between the record existing and being undefined and the record not existing, it is recommended to use the exists() method to test record existence instead.

Creating new records

New records are created using the add() method, as follows:

database.runTransaction(["fooBar", "baz"], (fooBar, baz) => {
  fooBar.add(newRecord, outOfLineKey)
  return baz.add(otherNewRecord) // in-line keys
}).then((id) => {
  // id is the primary key of the otherNewRecord
}).catch((error)) => {
  // something went wrong
})

Both the object stores using the in-line and the out-of-line keys can generate primary keys for new records automatically if the autoIncrement flag is set on the object store.

Updating existing records

Updating an existing record look pretty simillar to creating a new record, but is done using the put() method:

database.runTransaction(["fooBar", "baz"], (fooBar, baz) => {
  fooBar.put(newRecord, outOfLineKey)
  return baz.put(otherNewRecord) // in-line keys
}).then((id) => {
  // id is the primary key of the otherNewRecord
}).catch((error)) => {
  // something went wrong
})

Deleting records

Records can be deleted using the delete() method:

database.runTransaction("fooBar", (fooBar) => {
  fooBar.delete(primaryKeyOrKeyRangeOrFilter)
}).then(() => {
  // records have been deleted
}).catch((error)) => {
  // something went wrong
})

The delete() method allows deletion of multiple records by using a key range or a filter. Filters are described in detail here.