Reputation: 3
I need to save a json in a property of my schema, my schema:
export default class ListSchema {
static schema = {
name: 'Listas',
primaryKey: 'id',
properties: {
id: 'string',
name: 'string',
contents: 'string', // I need to save here, currently I left string
}
}
}
code that saves the list:
async function SaveList() {
const data = {
id: String(Date.now()),
name: List,
contents: JSON.stringify(AllTask) // I need to save json here
}
const realm = await getRealm()
realm.write(() => {
realm.create('Listas', data)
})
}
my json n has a definite size, and it goes something like this:
[{id: 'value', name:'value'}, {id: 'value', name:'value'} ...]
what should my schema look like?
Upvotes: 0
Views: 460
Reputation: 26
I'm using Realmdb in production with React Native and had the same doubt some time ago.
Basically you have two ways to do it.
The first and the more simple is convert your schema using JSON.stringify and save it in your field with type string, (Like you did) but when you wish get this value again, you will to convert again using JSON.parse, is boring but works well you have just to remeber.
The second option is create another schema and use it to insert values with object format.
const CarSchema = {
name: 'Car',
properties: {
make: 'string',
model: 'string',
miles: {type: 'int', default: 0},
}
};
const PersonSchema = {
name: 'Person',
properties: {
name: 'string',
cars: {type: 'list', objectType: 'Car'},
}
};
Above, we have two schema and if we insert a new data we have to do something like this.
realm.write(() => {
realm.create('Person', {
name: 'Joe',
// nested objects are created recursively
car: {make: 'Honda', model: 'Accord', drive: 'awd'},
});
});
This way is more eficient but is more hard to maintain the code.
Today we use the option 1, because is more simple and just one schema.
I hope that it help you.
Upvotes: 1