Search code examples
reactjsmobilerealmnative

How to create nested array in realm without key(React Native)


{
    "a": [
        [
            {
              "_id": "57e55b64016c3551c025abc1",
              "title": "Main Campus"
            },
            {
              "_id": "5810e2e27064497f74ad4874",
              "title": "Ahm Campus"
            },
            {
              "_id": "5d5d2633a1d0680620ac3cce",
              "title": "Baroda"
            },
            {
              "_id": "5d5d3af3a1d0680620ac3ef8",
              "title": "India"
            }
          ],
          [
            {
              "_id": "57e55b64016c3551c025abc1",
              "title": "Main Campus"
            },
            {
              "_id": "5810e2e27064497f74ad4874",
              "title": "Ahm Campus"
            },
            {
              "_id": "5d5d2633a1d0680620ac3cce",
              "title": "Baroda"
            },
            {
              "_id": "5d5d3af3a1d0680620ac3ef8",
              "title": "India"
            }
          ]

    ]
  }

How to create the schema in the realm(React native) for this type of JSON object. I tried all possible ways but did not found any specific solution. Basically, it is a nested array where the second array does not have any specific key(I tried with key it works fine but I want to do it without adding key).


Solution

  • You can use something like:

    const ParentSchema = {
      name: "parent",
      properties: {
        key: "string",
        values: "Value[]"
      }
    };
    
    const ValueSchema = {
      name: "Value",
      embedded: true,
      properties: {
        _id: "string",
        title: "string"
      }
    };
    

    You can insert objects like:

    realm.write(() => {
      realm.create("Parent", { key: "a", values: [
          { _id: "57e55b64016c3551c025abc1", title: "Main Campus" },
          { _id: "5810e2e27064497f74ad4874", title: "Ahm Campus" }
        ]
      });
    });
    

    Documentation: https://docs.mongodb.com/realm/node/data-model