Related Classes
- App
- Auth
- Collection
- Credentials
- Dictionary
- List
- MongoDBCollection
- Object
- Results
- Set
- User
- Worker
- MongoDB
- MongoDBDatabase
Constants
A re-export of the "bson" package, enabling access to the BSON types without requiring an explict dependency on the "bson" package.
Members
Indicates if this Realm has been closed.
Type:
boolean
Indicates if this Realm contains any objects.
Type:
boolean
Indicates if this Realm is in a write transaction.
Type:
boolean
Indicates if this Realm was opened as read-only.
Type:
boolean
The path to the file where this Realm is stored.
Type:
string
A normalized representation of the schema provided in the
Configuration
when this Realm was constructed.
Type:
[CanonicalObjectSchema, ...]
The current schema version of this Realm.
Type:
number
Get the latest set of flexible sync subscriptions.
Type:
Realm.App.Sybc.SubscriptionSet
Gets the sync session if this is a synced Realm
Type:
Session
Constructor
- config optional
- Type:
Configuration
Required when first creating the Realm.
-
Error
If anything in the provided
config
is invalid.
-
IncompatibleSyncedRealmError
when an incompatible synced Realm is opened
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.
In the case of query-based sync, config.schema
is required. An exception will be
thrown if config.schema
is not defined.
Parameters:
Throws:
Methods
-
Error
If an I/O error occured or method is not implemented.
- schema
- Type:
ObjectSchema
object describing the class
- config
- Type:
Configuration
-
Error
If anything in the provided
config
is invalid.
- config
- Type:
Configuration
The configuration for the Realm.
-
Error
if anything in the provided
config
is invalid.
- config
- Type:
Configuration
if no config is defined, it will open the default realm
-
Error
If anything in the provided
config
is invalid.
- a promise that will be resolved with the Realm instance when it's available.
- path
- Type:
string
The path to the file where the Realm database is stored.
- encryptionKey optional
- Type:
ArrayBuffer
orArrayBufferView
Required only when accessing encrypted Realms.
-
Error
When passing an invalid or non-matching encryption key.
- name
- Type:
string
The name of event that should cause the callback to be called. Currently, only the "change" and "schema" events are supported.
- callback
- Type:
callback(Realm, string)
orcallback(Realm, string, Schema)
Function to be called when a change event occurs. Each callback will only be called once per event, regardless of the number of times it was added.
-
Error
If an invalid event
name
is supplied, or ifcallback
is not a function.
-
Error
When already in write transaction
- type
- Type:
ObjectType
The type of Realm object to create.
- properties
- Type:
Object
Property values for all required properties without a default value.
- updateMode optional
- Type:
boolean
orstring
- Default:
'never'
Optional update mode. It can be one of the following values - 'never': Objects are only created. If an existing object exists, an exception is thrown. This is the default value. - 'all': If an existing object is found, all properties provided will be updated, any other properties will remain unchanged. - 'modified': If an existing object exists, only properties where the value has actually changed will be updated. This improves notifications and server side performance but also have implications for how changes across devices are merged. For most use cases, the behaviour will match the intuitive behaviour of how changes should be merged, but if updating an entire object is considered an atomic operation, this mode should not be used.
- object
- Type:
Realm.Object
or[Realm.Object, ...]
orRealm.List
orRealm.Results
- name
- Type:
string
the model name
- type
- Type:
ObjectType
The type of Realm object to search for.
- key
- Type:
number
orstring
The primary key value of the object to search for.
-
Error
If type passed into this method is invalid or if the object type did not have a
primaryKey
specified in itsObjectSchema
.
- type
- Type:
ObjectType
The type of Realm objects to retrieve.
-
Error
If type passed into this method is invalid or if the type is marked embedded or asymmetric.
- name optional
- Type:
string
The name of the event whose listeners should be removed. Currently, only the "change" and "schema" events are supported.
-
Error
When invalid event
name
is supplied
- name
- Type:
string
The event name. Currently, only the "change" and "schema" events are supported.
- callback
- Type:
callback(Realm, string)
orcallback(Realm, string, Schema)
Function that was previously added as a listener for this event through the
addListener
method.-
Error
If an invalid event
name
is supplied, or ifcallback
is not a function.
- callback
- Type:
function
- Input Realms may be local or partition-based synced, encrypted or non-encrypted
- Output Realms will be local or partition-based synced, encrypted or non-encrypted, depending on the configuration passed to the function
- {@link
Realm~Configuration | Configuration} config that describes the output Realm.
Copy any Realm files (i.e. *.realm
) bundled with the application from the application
directory into the application's documents directory, so that they can be opened and used
by Realm. If the file already exists in the documents directory, it will not be
overwritten, so this can safely be called multiple times.
This should be called before opening the Realm, in order to move the bundled Realm files into a place where they can be written to, for example:
// Given a bundled file, example.realm, this will copy example.realm (and any other .realm files)
// from the app bundle into the app's documents directory. If the file already exists, it will
// not be overwritten, so it is safe to call this every time the app starts.
Realm.copyBundledRealmFiles();
const realm = await Realm.open({
// This will open example.realm from the documents directory, with the bundled data in.
path: "example.realm"
});
This is only implemented for React Native.
Throws:
Creates a template object for a Realm model class where all optional fields are undefined
and all required
fields have the default value for the given data type, either the value set by the default
property in the
schema or the default value for the datatype if the schema doesn't specify one, i.e. 0
, false and ""
.
Parameters:
Delete the Realm file for the given configuration.
Parameters:
Throws:
boolean
Checks if the Realm already exists on disk.
Parameters:
Throws:
boolean
returns true
if the Realm exists on the device, false
if not.
ProgressPromise
Open a Realm asynchronously with a promise. If the Realm is synced, it will be fully
synchronized before it is available.
In the case of query-based sync, config.schema
is required. An exception will be
thrown if config.schema
is not defined.
Parameters:
Throws:
ProgressPromise
number
Get the current schema version of the Realm at the given path.
Parameters:
Throws:
number
version of the schema, or -1
if no Realm exists at path
.
Add a listener callback
for the specified event name
.
Parameters:
Throws:
Initiate a write transaction.
When doing a transaction, it is highly recommended to do error handling. If you don't handle errors, your data might become inconsistent. Error handling will often involve canceling the transaction.
Throws:
Example:
realm.beginTransaction();
try {
realm.create('Person', { name: 'Arthur Dent', origin: 'Earth' });
realm.create('Person', { name: 'Ford Prefect', origin: 'Betelgeuse Five' });
realm.commitTransaction();
} catch (e) {
realm.cancelTransaction();
throw e;
}
Cancel a write transaction.
beginTransaction()
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. The method is idempotent.
Commit a write transaction.
beginTransaction()
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.
Realm.Object
Create a new Realm object of the given type and with the specified properties. For object schemas annotated as asymmetric, no object is returned. The API for asymmetric object schema is subject to changes in the future.
Parameters:
Realm.Object
Deletes the provided Realm object, or each one inside the provided collection.
Parameters:
WARNING: This will delete all objects in the Realm!
Deletes a Realm model, including all of its objects.
If called outside a migration function, schema
and schemaVersion
are updated.
Parameters:
Realm.Object
or null
Searches for a Realm object by its primary key.
Parameters:
Throws:
Realm.Object
or null
if no object is found.
Realm.Results
Returns all objects of the given type
in the Realm.
Parameters:
Throws:
Realm.Results
that will live-update as objects are created and destroyed.
Remove all event listeners (restricted to the event name
, if provided).
Parameters:
Throws:
Remove the listener callback
for the specfied event name
.
Parameters:
Throws:
*
Synchronously call the provided callback
inside a write transaction. If an exception happens inside a transaction,
you’ll lose the changes in that transaction, but the Realm itself won’t be affected (or corrupted).
More precisely, beginTransaction()
and commitTransaction()
will be called
automatically. If any exception is thrown during the transaction cancelTransaction()
will
be called instead of commitTransaction()
and the exception will be re-thrown to the caller of write()
.
Nested transactions (calling write()
within write()
) is not possible.
Parameters:
*
Returned value from the callback.
Writes a compacted copy of the Realm with the given output configuration:
The destination Realm path cannot already exist.
Note that if this method is called from within a write transaction, the current data is written, not the data from the point when the previous write transaction was committed.
Parameters:
Type Definitions
- 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.- embedded optional
- Type:
boolean
True if the object type is embedded. An embedded object can be linked to by at most one parent object. Default value: false.
- properties
- Type:
{<string>: (PropertyType | ObjectSchemaProperty | ObjectSchema), ...}
An object where the keys are property names and the values represent the property type.
- name
- Type:
string
The name of this property.
- type
- Type:
PropertyType
The type of this property.
- property optional
- Type:
string
When using
"linkingObjects"
this value will represent the linked property on the linked object- optional
- Type:
boolean
Signals that this property may be assigned
null
orundefined
. For"list"
,"dictionary"
or"set"
properties of non-object types, this instead signals whether the values inside the list may be assignednull
orundefined
. This is not supported for"list"
or"set"
properties of object types and"linkingObjects"
properties.- indexed
- Type:
boolean
Signals that this property is indexed. Only supported for
"string"
,"int"
, and"bool"
properties.- mapTo
- Type:
string
The name of the alias this property has been set to.
- encryptionKey optional
- Type:
ArrayBuffer
orArrayBufferView
The 512-bit (64-byte) encryption key used to encrypt and decrypt all data in the Realm.
- onMigration 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 option is incompatible with
sync
. This function takes two arguments:oldRealm
- The Realm before migration is performed.newRealm
- The Realm that uses the latestschema
, which should be modified as necessary.
- deleteRealmIfMigrationNeeded optional
- Type:
boolean
- Default:
false
Specifies if this Realm should be deleted if a migration is needed. This option is not available on synced realms.
- shouldCompact 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) -usedSize
- The total bytes used by data in the file. It returnstrue
to indicate that an attempt to compact the file should be made. The compaction will be skipped if another process is accessing it.- onFirstOpen optional
- Type:
callback(realm)
The function called when opening a Realm for the first time. The function can populate the Realm prior to opening it. When calling the callback, the Realm will be in a write transaction. The callback takes one argument: -
realm
- The Realm- path optional
- Type:
string
- Default:
Realm.defaultPath
The path to the file where the Realm database should be stored. For synced Realms, a relative path is used together with app id and user id in order to avoid collisions with other apps or users. An absolute path is left untouched and on some platforms (iOS and Android) the app might not have permissions to create or open the file - permissions are not validated. If a relative path is specified, it is relative to
Realm.App~AppConfiguration.baseFilePath
.- fifoFilesFallbackPath optional
- Type:
string
Opening a Realm creates a number of FIFO special files in order to coordinate access to the Realm across threads and processes. If the Realm file is stored in a location that does not allow the creation of FIFO special files (e.g. FAT32 filesystems), then the Realm cannot be opened. In that case Realm needs a different location to store these files and this property defines that location. The FIFO special files are very lightweight and the main Realm file will still be stored in the location defined by the
path
property. This property is ignored if the directory defined bypath
allow FIFO special files.- 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. This option is incompatible with
sync
.- readOnly optional
- Type:
boolean
- Default:
false
Specifies if this Realm should be opened as read-only.
- disableFormatUpgrade optional
- Type:
boolean
- Default:
false
Specifies if this Realm's file format should be automatically upgraded if it was created with an older version of the Realm library. If set to
true
and a file format upgrade is required, an error will be thrown instead.- 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:
SyncConfiguration
Sync configuration parameters.
- schema
- Type:
ObjectSchema
Static property specifying object schema information.
- 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.- embedded optional
- Type:
boolean
True if the object type is embedded. An embedded object can be linked to by at most one parent object. Default value: false.
- asymmetric optional
- Type:
boolean
True if the object type is for asymmetric sync only. This implies that objects of the types are not stored locally and cannot be accessed locally.
- properties
- Type:
{<string>: (PropertyType | ObjectSchemaProperty | ObjectSchema), ...}
An object where the keys are property names and the values represent the property type.
- type
- Type:
PropertyType
The type of this property.
- objectType optional
- Type:
PropertyType
Required when
type
is"list"
,"set"
,"dictionary"
or"linkingObjects"
, and must match the type of an object in the same schema, or, for"list"
,"set"
or"dictionary"
, 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 inobjectType
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
orundefined
. For"list"
,"dictionary"
or"set"
properties of non-object types, this instead signals whether the values inside the list may be assignednull
orundefined
. This is not supported for"list"
or"set"
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.- mapTo optional
- Type:
string
Set this to the name of the underlying property in the Realm file if the Javascript property name is different than the name used in the Realm file. This can e.g. be used to have different naming convention in Javascript than what is being used in the Realm file. Reading and writing properties must be done using the public name. Queries can be done using both the public and the underlying property name.
- T
[]
indicates that the property is a Realm.List of values with of type T - T
<>
indicated that the property is a Realm.Set of values with type T - "bool"
- Type:
boolean
Property value may either be
true
orfalse
.- "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.
- "decimal128"
- Type:
Decimal128
Property value may be a
Decimal128
object (seebson
for details).- "objectId"
- Type:
ObjectId
Property valye may be an
ObjectId
object (seebson
for details).- "date"
- Type:
Date
Property may be assigned any
Date
instance.- "data"
- Type:
ArrayBuffer
Property may either be assigned an
ArrayBuffer
orArrayBufferView
(e.g.DataView
,Int8Array
,Float32Array
, etc.) instance, but will always be returned as anArrayBuffer
.- "list"
- Type:
Realm.List
Property may be assigned any ordered collection (e.g.
Array
,Realm.List
,Realm.Results
) of objects all matching theobjectType
specified in theObjectSchemaProperty
.- "set"
- Type:
Realm.Set
Property may be assigned an array (e.g.,
Array
) of objects all matching theobjectType
specified in theObjectSchemaProperty
.- "dictionary"
- Type:
Realm.Dictionary
Properties may be assigned to a key/value pair.
- "linkingObjects"
- Type:
Realm.Results
Property is read-only and always returns a
Realm.Results
of all the objects matching theobjectType
that are linking to the current object through theproperty
relationship specified inObjectSchemaProperty
.- "<ObjectType>"
- Type:
Realm.Object
A string that matches the
name
of an object in the same schema (seeObjectSchema
) – 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 assignednull
orundefined
).
The retreived schema from an open Realm might have a different structure as the input schema.
Type:
Object
Properties:
Type:
Object
Properties:
This describes the different options used to create a Realm
instance.
See Using Realm JS behind an HTTP Proxy for details on how use an HTTP forward proxy with this library.
Type:
Object
Properties:
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:
Type:
Object
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'}
setOfStrings: 'string<>',
setOfOptionalStrings: 'string?<>', // or {type: 'set', objectType: 'string'}
}
};
Type:
Object
Properties:
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
.
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).
Given a type, T, the following postfix operators may be used:
For example, optionalIntList: 'int?[]'
declares a property which is a list of
nullable integers, while optionalStringSet: 'string?<>'
declares a set of nullable strings.
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 "decimal128"
or "objectId"
or "date"
or "data"
or "list"
or "set"
or "linkingObjects"
or "<ObjectType>"