Skip to main content

RxDatabase

A RxDatabase-Object contains your collections and handles the synchronization of change-events.

Creation​

The database is created by the asynchronous .createRxDatabase() function of the core RxDB module. It has the following parameters:

import { createRxDatabase } from 'rxdb';
import { getRxStorageDexie } from 'rxdb/plugins/storage-dexie';

const db = await createRxDatabase({
name: 'heroesdb', // <- name
storage: getRxStorageDexie(), // <- RxStorage

/* Optional parameters: */
password: 'myPassword', // <- password (optional)
multiInstance: true, // <- multiInstance (optional, default: true)
eventReduce: true, // <- eventReduce (optional, default: false)
cleanupPolicy: {} // <- custom cleanup policy (optional)
});

name​

The database-name is a string which uniquely identifies the database. When two RxDatabases have the same name and use the same RxStorage, their data can be assumed as equal and they will share events between each other. Depending on the storage or adapter this can also be used to define the filesystem folder of your data.

storage​

RxDB works on top of an implementation of the RxStorage interface. This interface is an abstraction that allows you to use different underlying databases that actually handle the documents. Depending on your use case you might use a different storage with different tradeoffs in performance, bundle size or supported runtimes.

There are many RxStorage implementations that can be used depending on the JavaScript environment and performance requirements. For example you can use the Dexie RxStorage in the browser or use the LokiJS storage with the filesystem adapter in Node.js.


// use the Dexie.js RxStorage that stores data in IndexedDB.
import { getRxStorageDexie } from 'rxdb/plugins/storage-dexie';

const dbDexie = await createRxDatabase({
name: 'mydatabase',
storage: getRxStorageDexie()
});


// ...or use the LokiJS RxStorage with the indexeddb adapter.
import { getRxStorageLoki } from 'rxdb/plugins/storage-lokijs';
const LokiIncrementalIndexedDBAdapter = require('lokijs/src/incremental-indexeddb-adapter');

const dbLoki = await createRxDatabase({
name: 'mydatabase',
storage: getRxStorageLoki({
adapter: new LokiIncrementalIndexedDBAdapter()
})
});

password​

(optional) If you want to use encrypted fields in the collections of a database, you have to set a password for it. The password must be a string with at least 12 characters.

Read more about encryption here.

multiInstance​

(optional=true) When you create more than one instance of the same database in a single javascript-runtime, you should set multiInstance to true. This will enable the event sharing between the two instances. For example when the user has opened multiple browser windows, events will be shared between them so that both windows react to the same changes. multiInstance should be set to false when you have single-instances like a single Node.js-process, a react-native-app, a cordova-app or a single-window electron app which can decrease the startup time because no instance coordination has to be done.

eventReduce​

(optional=false)

One big benefit of having a realtime database is that big performance optimizations can be done when the database knows a query is observed and the updated results are needed continuously. RxDB uses the EventReduce Algorithm to optimize observer or recurring queries.

For better performance, you should always set eventReduce: true. This will also be the default in the next major RxDB version.

ignoreDuplicate​

(optional=false) If you create multiple RxDatabase-instances with the same name and same adapter, it's very likely that you have done something wrong. To prevent this common mistake, RxDB will throw an error when you do this. In some rare cases like unit-tests, you want to do this intentional by setting ignoreDuplicate to true.

const db1 = await createRxDatabase({
name: 'heroesdb',
storage: getRxStorageDexie(),
ignoreDuplicate: true
});
const db2 = await createRxDatabase({
name: 'heroesdb',
storage: getRxStorageDexie(),
ignoreDuplicate: true // this create-call will not throw because you explicitly allow it
});

Methods​

Observe with $​

Calling this will return an rxjs-Observable which streams all write events of the RxDatabase.

myDb.$.subscribe(changeEvent => console.dir(changeEvent));

exportJSON()​

Use this function to create a json-export from every piece of data in every collection of this database. You can pass true as a parameter to decrypt the encrypted data-fields of your document.

Before exportJSON() and importJSON() can be used, you have to add the json-dump plugin.

import { addRxPlugin } from 'rxdb';
import { RxDBJsonDumpPlugin } from 'rxdb/plugins/json-dump';
addRxPlugin(RxDBJsonDumpPlugin);
myDatabase.exportJSON()
.then(json => console.dir(json));

importJSON()​

To import the json-dumps into your database, use this function.

// import the dump to the database
emptyDatabase.importJSON(json)
.then(() => console.log('done'));

backup()​

Writes the current (or ongoing) database state to the filesystem. Read more

waitForLeadership()​

Returns a Promise which resolves when the RxDatabase becomes elected leader.

requestIdlePromise()​

Returns a promise which resolves when the database is in idle. This works similar to requestIdleCallback but tracks the idle-ness of the database instead of the CPU. Use this for semi-important tasks like cleanups which should not affect the speed of important tasks.


myDatabase.requestIdlePromise().then(() => {
// this will run at the moment the database has nothing else to do
myCollection.customCleanupFunction();
});

// with timeout
myDatabase.requestIdlePromise(1000 /* time in ms */).then(() => {
// this will run at the moment the database has nothing else to do
// or the timeout has passed
myCollection.customCleanupFunction();
});

destroy()​

Destroys the databases object-instance. This is to free up memory and stop all observers and replications. Returns a Promise that resolves when the database is destroyed.

await myDatabase.destroy();

remove()​

Wipes all documents from the storage. Use this to free up disc space.

await myDatabase.remove();
// database instance is now gone

// You can also clear a database without removing its instance
import { removeRxDatabase } from 'rxdb';
removeRxDatabase('mydatabasename', 'localstorage');

isRxDatabase​

Returns true if the given object is an instance of RxDatabase. Returns false if not.

import { isRxDatabase } from 'rxdb';
const is = isRxDatabase(myObj);