February 22, 2022
|
10
mins

Why Use Realm?

Sridhar Rajendran

What is Realm?

Realm is an open source mobile database, which is developer-friendly and an alternative to CoreData and SQLite. This platform/database is available for Swift, Objective-C, Java, Kotlin, C#, and JavaScript.

Why Use Realm?

Intuitive to Developers

Realm’s object-oriented data model is simple to learn, doesn’t need an ORM, and lets you write less code.

Designed for Offline Use

Realm’s local database stores data on-disk, so apps work smoothly on offline as they do online.

Built for Mobile

Realm is fully featured, lightweight, and efficiently uses memory, disk space, and battery life. This can be used as local database in mobile, which also interacts with remote database as MongoDB i.e. it can be kept as local database and other databases as remote database.


If you are looking for Swift development process, which requires realm as well as server less database access, your best bet is Realm MongoDB.


The power of realm with MongoDB atlas is humungous and one can synchronize their local database with remote database without their own code.

In this blog, we will see how to integrate realm with MongoDB atlas, React in native mobile app.

Let us consider an attendance tracker App that needs to record attendance, monitor attendance of students studying in a coaching center and send update to parents as a push message

The core schema required is the student schema. MongoDB Atlas and MongoDB Realm will work offline as well as online.

Schema should have following Properties_id and _partition and required fields. Properties contain attribute key and attribute data type.

Example schema:

{
"properties": {
"_id": {
"bsonType": "objectId"
},
"_partition": {
"bsonType": "string"
},
"createdBy": {
"bsonType": "string",
"elasticIndexed": true,
"elasticTransform": "username"
},
"createdDate": {
"bsonType": "double",
"elasticIndexed": true,
"elasticTransform": "date"
},
"docId": {
"bsonType": "string"
},
"docType": {
"bsonType": "string"
},
"id": {
"bsonType": "string"
},
"name": {
"bsonType": "string"
},
"dob": {
"bsonType": "string"
},
"age": {
"bsonType": "string"
},
"updatedBy": {
"bsonType": "string",
"elasticIndexed": true,
"elasticTransform": "username"
},
"updatedDate": {
"bsonType": "double",
"elasticIndexed": true,
"elasticTransform": "date"
}
},
"required": [
"_partition",
"docId"
],
"title": "StudentDoc"
}

MongoDB stores all the data of students under the same partition. Partition is nothing but a group. Here, we have an id and docId as unique value.

For e.g. there are 20 students in a particular class. Therefore, we have 20 documents that are grouped by one partition name called ‘student

How to configure app?

An app can be configured by creating an app in MongoDB atlas. Once configured, it will provide a unique app id, which can be used to log into the app to realm local database as well as communicate or synchronize with MongoDB.

Download Framework:

npm install realm

Realm Login

getRealmApp() {
      const appId = AppConstants.appId // Set Realm app ID here.
      Logger.infoLogEvent("Realm app ID: " + appId)
      const appConfig = {
          id: appId,
          timeout: 10000,
      };
      return new Realm.App(appConfig);
  }

const credentials = Realm
.Credentials.jwt(authToken);

const app = RealmSharedInstance
.instance.getRealmApp()

this.currentUser = await app.logIn(credentials);

Open Immediately:

We can open the downloaded document or we can create new one and then open. In most of the cases, we need to use this when app is offline. It is called as sync method.

Download Before Open:

Whenever internet is offline, we will use this configuration. It is async method. It will download the latest copy from remote to local.

Here is the code snippet

downloadRealmDoc = async (realmDetail: RealmDetail): Promise<RealmDetail> => {
      return new Promise(async (resolve, reject) => {
          try {
                  const config = {
                  sync: {
                      schema: [STUDENTSCHEMA],
                      user: this.currentUser,
                      partitionValue: realmDetail.partition,
                      newRealmFileBehavior:
this.downloadBefore
OpenBehaviorConfiguration,
                      existingRealmFileBehavior:
this.downloadBefore
OpenBehaviorConfiguration,
                      error: this.errorSync,
                      path: this.realmPath
                  }
              };
              this.currentRealm = await Realm.open(config)
              realmDetail.realm = this.currentRealm
              realmDetail.realm
.syncSession?.pause
              if (realmDetail.realm != undefined) {
                  Logger.infoLogEvent("
Downloaded realm document,
partition: " + realmDetail.partition)
                  resolve(realmDetail)
              } else {
                  reject("Unable to download realm");
              }
          } catch (err) {
              reject(err.message);
          }
      })
  }

Open Immediately

  static getFieldResultRealm = async (partition: string): Promise<Realm> => {
      return new Promise(async (resolve, reject) => {
          try {

              const config = {
                  sync: {
                      user: RealmSharedInstance
.instance.currentUser,
                      partitionValue: partition,
                      schema: [FieldResultDocSchema],
                  newRealmFileBehavior:
RealmSharedInstance.instance
.openImmediately
BehaviorConfiguration,
                      existingRealmFileBehavior:
RealmSharedInstance.instance
.openImmediately
BehaviorConfiguration,
                  }
              };
              const realm = await Realm.open(config)
              realm.syncSession?.pause
              resolve(realm)
          } catch (err) {
              reject(err.message);
          }
      })
}

‍To Create use the following snippet

realm.write(async () =>{
                              const createdDoc = realm.create("STUDENTDOC", {
                                  _id: doc._id,
}
}

To Update

realm.write(() => {
name:doc.name
}

Other BLOGS