Search code examples
javascriptreactjsreact-nativerealmrealm-js

Realm data type for dynamic key name pair and values


I am working with realm flexible sync in react native and i want to define schema for below json where key names are dynamic objectId and has set of properties so i tried dictionary and mixed but didn't worked. Also this group_taxes would have n of key values.

{
    "group_taxes": {
        // This one is dynamic object id as key which holds properties
        "63bbb1372aea3a5f887b4d0e": {
            "tax_id": {
                "$oid": "63bbb1372aea3a5f887b4d0e"
            },
            "tax_name": "CGST",
            "tax_rate": 10,
            "calculated_tax": 44,
            "tax_calculation": "PERCENTAGE"
        },
        "63bbb1372aea3a5f887b4d10": {
            "tax_id": {
                "$oid": "63bbb1372aea3a5f887b4d10"
            },
            "tax_name": "SGST",
            "tax_rate": 20,
            "calculated_tax": 20,
            "tax_calculation": "FLAT_VALUE"
        }
    }
}

What i tried to define in schema as below but didn't worked

{
  "group_taxes" : {
    "bsonType": "mixed"
  }
}

Solution

  • It appears you would like to store a List (aka 'array') of objects within the group_taxes property. The schema may look something like this

    {
      "title": "YourParentObject",
      "type": "object",
      "required": [
        "_id"
      ],
      "properties": {
        "_id": {
          "bsonType": "objectId"
        },
        "group_taxes": {
          "bsonType": "array",
          "child_object_list": {
            "bsonType": "objectId"
            //your child object properties; tax_id etc
          }
        }
      }
    }
    

    Keep in mind though - if the app is in development mode in the Realm Console, you can build your Realm models in code and the schema will automatically be created for you.

    If for example, you built this model in code

    class Tax extends Realm.Object {
      static schema = {
        name: 'Tax',
        properties: {
          tax_id: 'string',
          group_taxes: {
            type: 'list',
            objectType: 'TaxObject',
            optional: false,
          },
          tax_name: 'string',
        },
      };
    }
    

    a matching schema would be created in the console. (You would build the TaxObject separately in code as well)