5

I have data that looks like this

PersonJSONData = {
    "key1": {
        "name": "odo",
        "age": 10,
        "favorites": {
            "food": ["rice", "chocolate", "sugar"],
            "game": [],
            "color": ["red"]
        },
    "key2": {
        "name": "yana",
        "age": 50,
        "favorites": {
            "band": [],
            "food": ["eggs"],
            "book": ["ABC", "how to cook"]
        }
    },
    ...
}}

How do I write the schema in realm for react native?

const personSchema = {
    name: "Person",
    properties: {
        name: string,
        age: int,
        // favorites: I don't know what to write here??
    }
}

I tried using the type dictionary ("{}") but it's giving me an error:

[Error: A mixed property cannot contain an array of values.]

and when I used the type "mixed" I get this error:

[Error: Only realm instances are supported.]

Do I need to create an object type for that? If so, how to do it when I don't know for sure what the keys in favorites are?

Here is my code to create and write the instance.

const PersonInstance = new Realm(schema: [personSchema] })

function writePerson(){
    const personKeys = Object.keys(PersonJSONData)

    try { 
        personKeys.forEach((key) => {
        const { name, age, favorites } = PersonJSONData[key]
        
        PersonInstance.write(() => {
          PersonInstance.create('Person', {
            name, age, favorites
          })}
            
        })
    } catch(err) {
        // error handling
    }
}

or should I change how I write into the database instead? Can anyone help me with this? Thanks in advance.

Shoaib Khan
  • 1,020
  • 1
  • 5
  • 18
catreedle
  • 51
  • 6
  • Everything in Realm is an Object so yes, you will create an object that represents that data in code. Now the really important bit - you're asking how to create the object schema and fortunately that's covered in depth in the Getting Started Guide [Defining an Object Schema](https://docs.mongodb.com/realm/sdk/react-native/#define-an-object-schema) – Jay Jan 28 '22 at 21:37

1 Answers1

0
  const PERSON_SCHEMA = {
  name: 'person_schema',
  properties: {
    id: 'int?',
    data: {type: 'list', objectType: 'person_schema_data'},
  },
  primaryKey: 'id',
};

const PERSON_SCHEMA_DATA = {
  name: 'person_schema_data',
  properties: {
    name: 'string?',
    age: 'int?',
    favorites: {type: 'object', objectType: 'person_favorites'},
  },
};

const PERSON_SCHEMA_FAVORITES = {
  name: 'person_favorites',
  properties: {
    food: {type: 'list', objectType: 'string'},
    game: {type: 'list', objectType: 'string'},
    color: {type: 'list', objectType: 'string'},
  },
};

const realm = await Realm.open({
path:`person_schema_path`,
schema:[PERSON_SCHEMA,PERSON_SCHEMA_DATA,PERSON_SCHEMA_FAVORITES]
})
Rohit Chahal
  • 53
  • 1
  • 6