[React Native] - Realm Database
June 07, 2021 |REACT NATIVE - REALM DATABASE
Ref:
1. https://docs.mongodb.com/realm-legacy/docs/javascript/latest.html#examples
2. To do list example: https://hellokoding.com/todo-app-with-react-native-realm/
1. Open Realms
//Schema const PersonSchema = { name: 'Person',
properties: { realName: 'string', // required property displayName: 'string?', // optional property birthday: {type: 'date', optional: true}, // optional property } };
// Get the default Realm with support for our objects Realm.open({schema: [Car, Person]}) .then(realm => { // ...use the realm instance here }) .catch(error => { // Handle the error here if something went wrong });
// Open a realm at another path Realm.open({ path: 'anotherRealm.realm', schema: [CarSchema] }).then(/* ... */);
2. Get the current schema version
// Update to to the new schema Realm.open({schema: [UpdatedPersonSchema], schemaVersion: 1});//Get current version const currentVersion = Realm.schemaVersion(Realm.defaultPath);
2. List of properties
realm.write(() => { let charlie = realm.create('Person', { name: 'Charlie', testScores: [100.0] }); // Charlie had an excused absense for the second test and was allowed to skip it charlie.testScores.push(null); // And then he didn't do so well on the third test charlie.testScores.push(70.0); });
3. Relationship
* To-One Relationship
const PersonSchema = {
name: 'Person',
properties: {
// The following property definitions are equivalent
car: {type: 'Car'},
van: 'Car',
}
};
realm.write(() => {
const nameString = person.car.name;
person.car.miles = 1100;
// create a new Car by setting the property to an object
// with all of the required fields
person.van = {make: 'Ford', model: 'Transit'};
// set both properties to the same car instance
person.car = person.van;
});
* To-Many Relationships
const PersonSchema = {
name: 'Person',
properties: {
// The following property definitions are equivalent
cars: {type: 'list', objectType: 'Car'},
vans: 'Car[]'
}
}
let carList = person.cars;
// Add new cars to the list
realm.write(() => {
carList.push({make: 'Honda', model: 'Accord', miles: 100});
carList.push({make: 'Toyota', model: 'Prius', miles: 200});
});
let secondCar = carList[1].model; // access using an array index
4. Query
* Get max value in Collection List.
For example: you want to get max of id Person in List. you can do like that
const personList = realm ? realm.objects('Personal') : null;
let idIdx = 0;
if (personList != null && personList.length != 0) {
idIdx = personList.max('id');
idIdx++;
}
* Passed para to query
Each subsequent argument is used by the placeholders (e.g. $0, $1, $2, …) in the query.
let person = personList.filtered('id=$0', id);
is updating