Dexie Constructor
Dexie.js (Official home page: dexie.org) is a library that makes it super simple to use indexedDB - the standard client-side database in browsers. Read more about Dexie on it’s README or at the home page.
Dexie
is the main class and the default export of the library. An instance of this class represents an indexedDB database connection.
Syntax
var db = new Dexie(databaseName, options?);
Parameters
Parameter | Description |
---|---|
dbName: String | Database name |
options: Object (optional) | API Options |
Options
Option | Description |
---|---|
addons: Array |
Explicitly define the addons to activate for this db instance |
autoOpen: boolean | Default true. Whether database will open automatically on first query. |
indexedDB: IDBFactory | Supply an alternate implementation of indexedDB. If supplying this, also supply IDBKeyRange that works with that implementation. |
IDBKeyRange: IDBKeyRange | An implementation of the IDBKeyRange interface that works with provided indexedDB implementation. |
allowEmptyDB: boolean | If opening in dynamic mode (not defining a schema) the call to db.open() will normally reject if the database didn’t exist and this option is false or not set. By setting this option to true, Dexie.open() will succeed to create a new empty database when opening it dynamically. |
modifyChunkSize: number | (since 3.1.0-alpha) Override the default value of 2000 rows per chunk used by Collection.modify(). See FR #1152. |
chromeTransactionDurability: ‘default’ | ‘strict’ | ‘relaxed’ | (since 3.2.0-beta.3) Override the default transaction durability in Chrome versions >=83. See FR #1018 |
cache: ‘cloned’ | ‘immutable’ | ‘disabled’ | (since 4.0.1-alpha.17) Override the default caching behavior. Default is ‘cloned’ (dexie@>4 only) and allows optimistic updates to trigger liveQueries before transactions commit. ‘immutable’ also enables optimistic updates with some optimization - less cloning and less memory consumption but return values from read-operations from live queries are frozen. ‘disabled’ gives same behavior as dexie@3 with no cache or optimistic updates. |
If the ‘addons’ option is omitted, it will default to the value of Dexie.addons.
Return Value
Sample
// Declare db instance
var db = new Dexie("MyDatabase");
// Define Database Schema
db.version(1).stores({
friends: "++id, name, age, isCloseFriend",
notes: "++id, title, date, *items",
});
// Interact With Database
db.transaction("rw", db.friends, db.notes, function* () {
// Let's add some data to db:
var friend1Id = yield db.friends.add({
name: "Camilla",
age: 25,
isCloseFriend: 1,
});
var friend2Id = yield db.friends.add({
name: "Ban Ki-moon",
age: 70,
isCloseFriend: 0,
});
var noteId = yield db.notes.add({
title: "Shop tomorrow",
date: new Date(),
items: ["milk", "butter"],
});
// Let's query the db
var closeFriends = yield db.friends
.where("isCloseFriend")
.equals(1)
.toArray();
console.log("Close friends:" + closeFriends.map((f) => f.name));
var toShop = yield db.notes
.where("title")
.startsWithIgnoreCase("shop")
.toArray();
console.log("Shopping list: " + toShop.map((note) => note.items));
}).catch(function (err) {
// Catch any error event or exception and log it:
console.error(err.stack || err);
});
Sample: Open existing database ‘as is’
new Dexie("MyDatabase")
.open()
.then(function (db) {
console.log("Found database: " + db.name);
console.log("Database version: " + db.verno);
db.tables.forEach(function (table) {
console.log("Found table: " + table.name);
console.log("Table Schema: " + JSON.stringify(table.schema, null, 4));
});
})
.catch("NoSuchDatabaseError", function (e) {
// Database with that name did not exist
console.error("Database not found");
})
.catch(function (e) {
console.error("Oh uh: " + e);
});
Sample: Instantiate a Dexie with custom addon
// Define the addon
function myForEachAddon(db) {
db.Collection.prototype.forEach = function (callback) {
// Make the forEach() method just an alias of the existing
// each() method:
return this.each(callback);
});
}
// Register it (optional)
Dexie.addons.push(myForEachAddon);
// Use it:
var db = new Dexie('dbname');
db.version(1).stores({friends: 'name'});
db.transaction('rw', db.friends, function () {
db.friends.clear();
db.friends.bulkAdd([{name: "Foo"},{name: "Bar"}]);
}).then(function() {
db.friends
.where('name')
.anyOfIgnoreCase('foo','bar')
.forEach(friend => {
console.log(friend.name);
});
}).catch(ex => {
console.error(ex);
});
How options tells how to apply addons:
// Open normally. Registered addons will be invoked automatically.
var db1 = new Dexie("dbname");
// Explicitly tell Dexie to ignore registered addons:
var db2 = new Dexie("dbname", { addons: [] });
// Explicitly tell Dexie to use just your set of addons:
var db3 = new Dexie("dbname", { addons: [myForEachAddon] });
Methods
version()
Specify the database schema (object stores and indexes) for a certain version.
on()
Subscribe to events
open()
Open database and make it start functioning.
table()
Returns an object store to operate on
transaction()
Start a database transaction
close()
Close the database
delete()
Delete the database
isOpen()
Returns true if database is open.
hasFailed()
Returns true if database failed to open.
backendDB()
Returns the native IDBDatabase instance.
vip()
Enable on(‘ready’) subscribers to use db before open() is complete.
Properties
name
The database name.
[table]
Each object store defined in version().stores() gets a Table instance named by the object store.
tables
Javascript Array containing all Table instances.
verno
Version of current database
Static Methods
Dexie.async()
Declare an async function in today’s modern browsers (2015) without the need for a transpiler.
Dexie.spawn()
Spawn an async function in today’s modern browsers (2015) without the need for a transpiler.
Dexie.delete()
Delete a database.
Dexie.getDatabaseNames()
List all database names at current origin.
Dexie.exists()
Detect whether a database with the given name exists.
Dexie.getByKeyPath()
Retrieve a property from an object given a key path.
Dexie.setByKeyPath()
Modify a property in an object given a key path and value.
Dexie.delByKeyPath()
Delete a property from an object given a key path.
Dexie.shallowClone()
Shallow clones an object.
Dexie.deepClone()
Deep clones an object.
Dexie.ignoreTransaction()
Create a a new scope where current transaction is ignored.
Dexie.override()
Override existing method and be able to call the original method.
Dexie.defineClass()
Creates a function and populates its prototype with given structure.
Dexie.derive()
Fixes the prototype chain for OOP inheritance.
Dexie.extend()
Set given additional properties into given object.
Dexie.Events()
Create a set of events to subscribe to and fire.
Static Properties
addons
Array of extended constructors.
debug
Get / set debug mode.
semVer
Contains the semantic version string from package.json.
version
Contains the version number of Dexie as a numeric comparable decimal value.
Table of Contents
- API Reference
- Access Control in Dexie Cloud
- Add demo users
- Add public data
- Authentication in Dexie Cloud
- Best Practices
- Building Addons
- Collection
- Collection.and()
- Collection.clone()
- Collection.count()
- Collection.delete()
- Collection.desc()
- Collection.distinct()
- Collection.each()
- Collection.eachKey()
- Collection.eachPrimaryKey()
- Collection.eachUniqueKey()
- Collection.filter()
- Collection.first()
- Collection.keys()
- Collection.last()
- Collection.limit()
- Collection.modify()
- Collection.offset()
- Collection.or()
- Collection.primaryKeys()
- Collection.raw()
- Collection.reverse()
- Collection.sortBy()
- Collection.toArray()
- Collection.uniqueKeys()
- Collection.until()
- Compound Index
- Consistency in Dexie Cloud
- Consistent add() operator
- Consistent remove() operator
- Consistent replacePrefix() operator
- Consuming Dexie as a module
- Custom Emails in Dexie Cloud
- DBCore
- DBCoreAddRequest
- DBCoreCountRequest
- DBCoreCursor
- DBCoreDeleteRangeRequest
- DBCoreDeleteRequest
- DBCoreGetManyRequest
- DBCoreGetRequest
- DBCoreIndex
- DBCoreKeyRange
- DBCoreMutateRequest
- DBCoreMutateResponse
- DBCoreOpenCursorRequest
- DBCorePutRequest
- DBCoreQuery
- DBCoreQueryRequest
- DBCoreQueryResponse
- DBCoreRangeType
- DBCoreSchema
- DBCoreTable
- DBCoreTableSchema
- DBCoreTransaction
- DBCoreTransactionMode
- DBPermissionSet
- Deprecations
- Derived Work
- Design
- Dexie Cloud API
- Dexie Cloud API Limits
- Dexie Cloud Best Practices
- Dexie Cloud CLI
- Dexie Cloud Docs
- Dexie Cloud REST API
- Dexie Cloud Web Hooks
- Dexie Constructor
- Dexie.AbortError
- Dexie.BulkError
- Dexie.ConstraintError
- Dexie.DataCloneError
- Dexie.DataError
- Dexie.DatabaseClosedError
- Dexie.IncompatiblePromiseError
- Dexie.InternalError
- Dexie.InvalidAccessError
- Dexie.InvalidArgumentError
- Dexie.InvalidStateError
- Dexie.InvalidTableError
- Dexie.MissingAPIError
- Dexie.ModifyError
- Dexie.NoSuchDatabaseErrorError
- Dexie.NotFoundError
- Dexie.Observable
- Dexie.Observable.DatabaseChange
- Dexie.OpenFailedError
- Dexie.PrematureCommitError
- Dexie.QuotaExceededError
- Dexie.ReadOnlyError
- Dexie.SchemaError
- Dexie.SubTransactionError
- Dexie.Syncable
- Dexie.Syncable.IDatabaseChange
- Dexie.Syncable.IPersistentContext
- Dexie.Syncable.ISyncProtocol
- Dexie.Syncable.StatusTexts
- Dexie.Syncable.Statuses
- Dexie.Syncable.registerSyncProtocol()
- Dexie.TimeoutError
- Dexie.TransactionInactiveError
- Dexie.UnknownError
- Dexie.UnsupportedError
- Dexie.UpgradeError()
- Dexie.VersionChangeError
- Dexie.VersionError
- Dexie.[table]
- Dexie.addons
- Dexie.async()
- Dexie.backendDB()
- Dexie.close()
- Dexie.currentTransaction
- Dexie.debug
- Dexie.deepClone()
- Dexie.defineClass()
- Dexie.delByKeyPath()
- Dexie.delete()
- Dexie.derive()
- Dexie.events()
- Dexie.exists()
- Dexie.extend()
- Dexie.fakeAutoComplete()
- Dexie.getByKeyPath()
- Dexie.getDatabaseNames()
- Dexie.hasFailed()
- Dexie.ignoreTransaction()
- Dexie.isOpen()
- Dexie.js
- Dexie.name
- Dexie.on()
- Dexie.on.blocked
- Dexie.on.close
- Dexie.on.error
- Dexie.on.populate
- Dexie.on.populate-(old-version)
- Dexie.on.ready
- Dexie.on.storagemutated
- Dexie.on.versionchange
- Dexie.open()
- Dexie.override()
- Dexie.semVer
- Dexie.setByKeyPath()
- Dexie.shallowClone()
- Dexie.spawn()
- Dexie.table()
- Dexie.tables
- Dexie.transaction()
- Dexie.transaction()-(old-version)
- Dexie.use()
- Dexie.verno
- Dexie.version
- Dexie.version()
- Dexie.vip()
- Dexie.waitFor()
- DexieCloudOptions
- DexieError
- Docs Home
- Download
- EntityTable
- Export and Import Database
- Get started with Dexie in Angular
- Get started with Dexie in React
- Get started with Dexie in Svelte
- Get started with Dexie in Vue
- Hello World
- How To Use the StorageManager API
- Inbound
- IndexSpec
- Indexable Type
- IndexedDB on Safari
- Invite
- Member
- Migrating existing DB to Dexie
- MultiEntry Index
- PersistedSyncState
- Privacy Policy
- Promise
- Promise.PSD
- Promise.catch()
- Promise.finally()
- Promise.on.error
- Promise.onuncatched
- Questions and Answers
- Realm
- Releasing Dexie
- Road Map
- Road Map: Dexie 5.0
- Road Map: Dexie Cloud
- Role
- Run Dexie Cloud on Own Servers
- Sharding and Scalability
- Simplify with yield
- Support Ukraine
- SyncState
- Table
- Table Schema
- Table.add()
- Table.bulkAdd()
- Table.bulkDelete()
- Table.bulkGet()
- Table.bulkPut()
- Table.bulkUpdate()
- Table.clear()
- Table.count()
- Table.defineClass()
- Table.delete()
- Table.each()
- Table.filter()
- Table.get()
- Table.hook('creating')
- Table.hook('deleting')
- Table.hook('reading')
- Table.hook('updating')
- Table.limit()
- Table.mapToClass()
- Table.name
- Table.offset()
- Table.orderBy()
- Table.put()
- Table.reverse()
- Table.schema
- Table.toArray()
- Table.toCollection()
- Table.update()
- Table.where()
- The main limitations of IndexedDB
- Transaction
- Transaction.abort()
- Transaction.on.abort
- Transaction.on.complete
- Transaction.on.error
- Transaction.table()
- Tutorial
- Typescript
- Typescript (old)
- Understanding the basics
- UserLogin
- Version
- Version.stores()
- Version.upgrade()
- WhereClause
- WhereClause.above()
- WhereClause.aboveOrEqual()
- WhereClause.anyOf()
- WhereClause.anyOfIgnoreCase()
- WhereClause.below()
- WhereClause.belowOrEqual()
- WhereClause.between()
- WhereClause.equals()
- WhereClause.equalsIgnoreCase()
- WhereClause.inAnyRange()
- WhereClause.noneOf()
- WhereClause.notEqual()
- WhereClause.startsWith()
- WhereClause.startsWithAnyOf()
- WhereClause.startsWithAnyOfIgnoreCase()
- WhereClause.startsWithIgnoreCase()
- db.cloud.configure()
- db.cloud.currentUser
- db.cloud.currentUserId
- db.cloud.events.syncComplete
- db.cloud.invites
- db.cloud.login()
- db.cloud.logout()
- db.cloud.options
- db.cloud.permissions()
- db.cloud.persistedSyncState
- db.cloud.roles
- db.cloud.schema
- db.cloud.sync()
- db.cloud.syncState
- db.cloud.userInteraction
- db.cloud.usingServiceWorker
- db.cloud.version
- db.cloud.webSocketStatus
- db.members
- db.realms
- db.roles
- db.syncable.connect()
- db.syncable.delete()
- db.syncable.disconnect()
- db.syncable.getOptions()
- db.syncable.getStatus()
- db.syncable.list()
- db.syncable.on('statusChanged')
- db.syncable.setFilter()
- dexie-cloud-addon
- dexie-react-hooks
- liveQuery()
- unhandledrejection-event
- useLiveQuery()
- useObservable()
- usePermissions()