Realm

A Realm instance represents a Realm database.

const Realm = require('realm');

Related Classes

Collection
List
Object
Results
Sync
Realm.defaultPath
static

The default path where to create and access the Realm file.

Type:
string
empty
readonly

Indicates if this Realm contains any objects.

Type:
boolean
isInTransaction
readonly

Indicates if this Realm is in a write transaction.

Type:
boolean
path
readonly

The path to the file where this Realm is stored.

Type:
string
readOnly
readonly

Indicates if this Realm was opened as read-only.

Type:
boolean
schema
readonly

A normalized representation of the schema provided in the Configuration when this Realm was constructed.

Type:
[ObjectSchema, ...]
schemaVersion
readonly

The current schema version of this Realm.

Type:
number
syncSession

Gets the sync session if this is a synced Realm

Type:
Session
new Realm(config)

Create a new Realm instance using the provided config. If a Realm does not yet exist at config.path (or Realm.defaultPath if not provided), then this constructor will create it with the provided config.schema (which is required in this case). Otherwise, the instance will access the existing Realm from the file at that path. In this case, config.schema is optional or not have changed, unless config.schemaVersion is incremented, in which case the Realm will be automatically migrated to use the new schema.

Parameters:
  • config optional
Realm.deleteFile(config)
static

Delete the Realm file for the given configuration.

Parameters:
Throws:
  • Error
    • If anything in the provided config is invalid.

Realm.open(config)ProgressPromise
static

Open a Realm asynchronously with a promise. If the Realm is synced, it will be fully synchronized before it is available.

Parameters:
Returns: ProgressPromise
  • a promise that will be resolved with the Realm instance when it's available.
Realm.openAsync(config, callback, progressCallback)
static

Open a Realm asynchronously with a callback. If the Realm is synced, it will be fully synchronized before it is available.

Parameters:
  • callback
    • Type: callback(error, realm)
    • will be called when the Realm is ready.

  • progressCallback optional
    • Type: callback(transferred, transferable)
    • an optional callback for download progress notifications

Throws:
  • Error
    • If anything in the provided config is invalid

  • IncompatibleSyncedRealmError
    • when an incompatible synced Realm is opened

Realm.schemaVersion(path, encryptionKey)number
static

Get the current schema version of the Realm at the given path.

Parameters:
  • path
    • Type: string
    • The path to the file where the Realm database is stored.

  • encryptionKey optional
    • Type: ArrayBuffer or ArrayBufferView
    • Required only when accessing encrypted Realms.

Throws:
  • Error
    • When passing an invalid or non-matching encryption key.

Returns: number version of the schema, or -1 if no Realm exists at path.
addListener(name, callback)

Add a listener callback for the specified event name.

Parameters:
  • name
    • Type: string
    • The name of event that should cause the callback to be called. Currently, only the "change" event supported.

  • callback
    • Type: callback(Realm, string)
    • Function to be called when the event occurs. Each callback will only be called once per event, regardless of the number of times it was added.

Throws:
  • Error
    • If an invalid event name is supplied, or if callback is not a function.

beginTransaction()

Initiate a write transaction.

Throws:
  • Error
    • When already in write transaction

cancelTransaction()

Cancel a write transaction.

close()

Closes this Realm so it may be re-opened with a newer schema version. All objects and collections from this Realm are no longer valid after calling this method.

commitTransaction()

Commit a write transaction.

compact()true

Replaces all string columns in this Realm with a string enumeration column and compacts the database file.

Cannot be called from a write transaction.

Compaction will not occur if other Realm instances exist.

While compaction is in progress, attempts by other threads or processes to open the database will wait.

Be warned that resource requirements for compaction is proportional to the amount of live data in the database. Compaction works by writing the database contents to a temporary database file and then replacing the database with the temporary one.

Returns: true if compaction succeeds.
create(type, properties, update)Realm.Object

Create a new Realm object of the given type and with the specified properties.

Parameters:
  • type
    • Type: ObjectType
    • The type of Realm object to create.

  • properties
    • Type: Object
    • Property values for all required properties without a default value.

  • update optional
    • Type: boolean
    • Default: false
    • Signals that an existing object with matching primary key should be updated. Only the primary key property and properties which should be updated need to be specified. All missing property values will remain unchanged.

Returns: Realm.Object
delete(object)

Deletes the provided Realm object, or each one inside the provided collection.

Parameters:
deleteAll()

WARNING: This will delete all objects in the Realm!

deleteModel(name)

Deletes a Realm model, including all of its objects.

Parameters:
  • name
    • Type: string
    • the model name

objectForPrimaryKey(type, key)Realm.Object or undefined

Searches for a Realm object by its primary key.

Parameters:
  • type
    • Type: ObjectType
    • The type of Realm object to search for.

  • key
    • Type: number or string
    • The primary key value of the object to search for.

Throws:
  • Error
    • If type passed into this method is invalid or if the object type did not have a primaryKey specified in its ObjectSchema.

Returns: Realm.Object or undefined if no object is found.
objects(type)Realm.Results

Returns all objects of the given type in the Realm.

Parameters:
  • type
    • Type: ObjectType
    • The type of Realm objects to retrieve.

Throws:
  • Error
    • If type passed into this method is invalid.

Returns: Realm.Results that will live-update as objects are created and destroyed.
removeAllListeners(name)

Remove all event listeners (restricted to the event name, if provided).

Parameters:
  • name optional
    • Type: string
    • The name of the event whose listeners should be removed. Currently, only the "change" event supported.

Throws:
  • Error
    • When invalid event name is supplied

removeListener(name, callback)

Remove the listener callback for the specfied event name.

Parameters:
  • name
    • Type: string
    • The event name. Currently, only the "change" event supported.

  • callback
    • Type: callback(Realm, string)
    • Function that was previously added as a listener for this event through the addListener method.

Throws:
  • Error
    • If an invalid event name is supplied, or if callback is not a function.

subscribeToObjects(type, query)Promise

If the Realm is a partially synchronized Realm, fetch and synchronize the objects of a given object type that match the given query (in string format).

Partial synchronization is a tech preview. Its APIs are subject to change.

Parameters:
  • type
    • Type: ObjectType
    • The type of Realm objects to retrieve.

  • query
    • Type: string
    • Query used to filter objects.

Returns: Promise
  • a promise that will be resolved with the Realm.Results instance when it's available.
write(callback)

Synchronously call the provided callback inside a write transaction.

Parameters:
  • callback
    • Type: function
Configuration

This describes the different options used to create a Realm instance.

Type:
Object
Properties:
  • encryptionKey optional
    • Type: ArrayBuffer or ArrayBufferView
    • The 512-bit (64-byte) encryption key used to encrypt and decrypt all data in the Realm.

  • migration optional
    • Type: callback(Realm, Realm)
    • The function to run if a migration is needed. This function should provide all the logic for converting data models from previous schemas to the new schema. This function takes two arguments:

      • oldRealm - The Realm before migration is performed.
      • newRealm - The Realm that uses the latest schema, which should be modified as necessary.
  • deleteRealmIfMigrationNeeded optional
    • Type: boolean
    • Default: false
    • Specifies if this Realm should be deleted if a migration is needed.

  • shouldCompactOnLaunch optional
    • Type: callback(number, number)
    • The function called when opening a Realm for the first time during the life of a process to determine if it should be compacted before being returned to the user. The function takes two arguments:

      - `totalSize` - The total file size (data + free space)
      - `unusedSize` - The total bytes used by data in the file.

      It returns true to indicate that an attempt to compact the file should be made. The compaction will be skipped if another process is accessing it.

  • path optional
    • Type: string
    • Default: Realm.defaultPath
    • The path to the file where the Realm database should be stored.

  • inMemory optional
    • Type: boolean
    • Default: false
    • Specifies if this Realm should be opened in-memory. This still requires a path (can be the default path) to identify the Realm so other processes can open the same Realm. The file will also be used as swap space if the Realm becomes bigger than what fits in memory, but it is not persistent and will be removed when the last instance is closed.

  • readOnly optional
    • Type: boolean
    • Default: false
    • Specifies if this Realm should be opened as read-only.

  • schema optional
    • Type: [(ObjectClass | ObjectSchema), ...]
    • Specifies all the object types in this Realm. Required when first creating a Realm at this path. If omitted, the schema will be read from the existing Realm file.

  • schemaVersion optional
    • Type: number
    • Required (and must be incremented) after changing the schema.

  • sync optional
    • Type: Object
    • Sync configuration parameters with the following child properties:

      • user - A User object obtained by calling Realm.Sync.User.login
      • url - A string which contains a valid Realm Sync url
      • error - A callback function which is called in error situations. The error callback can take up to five optional arguments: name, message, isFatal, category, and code.
      • validate_ssl - Indicating if SSL certificates must be validated
      • ssl_trust_certificate_path - A path where to find trusted SSL certificates
      • open_ssl_verify_callback - A callback function used to accept or reject the server's SSL certificate. open_ssl_verify_callback is called with an object of type

         {
           serverAddress: String,
           serverPort: Number,
           pemCertificate: String,
           acceptedByOpenSSL: Boolean,
           depth: Number
         }

        The return value of open_ssl_verify_callback decides whether the certificate is accepted (true) or rejected (false). The open_ssl_verify_callback function is only respected on platforms where OpenSSL is used for the sync client, e.g. Linux. The open_ssl_verify_callback function is not allowed to throw exceptions. If the operations needed to verify the certificate lead to an exception, the exception must be caught explicitly before returning. The return value would typically be false in case of an exception.

        When the sync client has received the server's certificate chain, it presents every certificate in the chain to the open_ssl_verify_callback function. The depth argument specifies the position of the certificate in the chain. depth = 0 represents the actual server certificate. The root certificate has the highest depth. The certificate of highest depth will be presented first.

        acceptedByOpenSSL is true if OpenSSL has accepted the certificate, and false if OpenSSL has rejected it. It is generally safe to return true when acceptedByOpenSSL is true. If acceptedByOpenSSL is false, an independent verification should be made.

        One possible way of using the open_ssl_verify_callback function is to embed the known server certificate in the client and accept the presented certificate if and only if it is equal to the known certificate.

        The purpose of open_ssl_verify_callback is to enable custom certificate handling and to solve cases where OpenSSL erroneously rejects valid certificates possibly because OpenSSL doesn't have access to the proper trust certificates.

      • partial - Whether this Realm should be opened in 'partial synchronization' mode. Partial synchronisation only synchronizes those objects that match the query specified in contrast to the normal mode of operation that synchronises all objects in a remote Realm. Partial synchronization is a tech preview. Its APIs are subject to change.
ObjectClass

Realm objects will inherit methods, getters, and setters from the prototype of this constructor. It is highly recommended that this constructor inherit from Realm.Object.

Type:
Class
Properties:
  • schema
    • Type: ObjectSchema
    • Static property specifying object schema information.

ObjectSchema
Type:
Object
Properties:
  • name
    • Type: string
    • Represents the object type.

  • primaryKey optional
    • Type: string
    • The name of a "string" or "int" property that must be unique across all objects of this type within the same Realm.

  • properties
Example:
let MyClassSchema = {
    name: 'MyClass',
    primaryKey: 'pk',
    properties: {
        pk: 'int',
        optionalFloatValue: 'float?' // or {type: 'float', optional: true}
        listOfStrings: 'string[]',
        listOfOptionalDates: 'date?[]',
        indexedInt: {type: 'int', indexed: true}

        linkToObject: 'MyClass',
        listOfObjects: 'MyClass[]', // or {type: 'list', objectType: 'MyClass'}
        objectsLinkingToThisObject: {type: 'linkingObjects', objectType: 'MyClass', property: 'linkToObject'}
    }
};
ObjectSchemaProperty
Type:
Object
Properties:
  • objectType optional
    • Type: PropertyType
    • Required when type is "list" or "linkingObjects", and must match the type of an object in the same schema, or, for "list" only, any other type which may be stored as a Realm property.

  • property optional
    • Type: string
    • Required when type is "linkingObjects", and must match the name of a property on the type specified in objectType that links to the type this property belongs to.

  • default optional
    • Type: any
    • The default value for this property on creation when not otherwise specified.

  • optional optional
    • Type: boolean
    • Signals if this property may be assigned null or undefined. For "list" properties of non-object types, this instead signals whether the values inside the list may be assigned null or undefined. This is not supported for "list" properties of object types and "linkingObjects" properties.

  • indexed optional
    • Type: boolean
    • Signals if this property should be indexed. Only supported for "string", "int", and "bool" properties.

ObjectType

The type of an object may either be specified as a string equal to the name in a ObjectSchema definition, or a constructor that was specified in the configuration schema.

Type:
string or ObjectClass
PropertyType

A property type may be specified as one of the standard builtin types, or as an object type inside the same schema.

When specifying property types in an object schema, you may append ? to any of the property types to indicate that it is optional (i.e. it can be null in addition to the normal values) and [] to indicate that it is instead a list of that type. For example, optionalIntList: 'int?[]' would declare a property which is a list of nullable integers. The property types reported by collections and in a Realm's schema will never use these forms.

Type:
"bool" or "int" or "float" or "double" or "string" or "date" or "data" or "list" or "linkingObjects" or "<ObjectType>"
Properties:
  • "bool"
    • Type: boolean
    • Property value may either be true or false.

  • "int"
    • Type: number
    • Property may be assigned any number, but will be stored as a round integer, meaning anything after the decimal will be truncated.

  • "float"
    • Type: number
    • Property may be assigned any number, but will be stored as a float, which may result in a loss of precision.

  • "double"
    • Type: number
    • Property may be assigned any number, and will have no loss of precision.

  • "string"
    • Type: string
    • Property value may be any arbitrary string.

  • "date"
    • Type: Date
    • Property may be assigned any Date instance.

  • "data"
    • Type: ArrayBuffer
    • Property may either be assigned an ArrayBuffer or ArrayBufferView (e.g. DataView, Int8Array, Float32Array, etc.) instance, but will always be returned as an ArrayBuffer.

  • "linkingObjects"
  • "<ObjectType>"
    • Type: Realm.Object
    • A string that matches the name of an object in the same schema (see ObjectSchema) – this property may be assigned any object of this type from inside the same Realm, and will always be optional (meaning it may also be assigned null or undefined).