Search code examples
javascriptnode.jsrealmrealm-js

How to collect data from multiple schemas ? - Realm


I am new in Realm database, it's amazing, and I've few doubts about the relationship thing. Rather than asking each doubt, I prefer to understand it from an example. Below given a sample schema copied from realm javascript docs.

const CarSchema = {
  name: 'Car',
  properties: {
    make:  'string',
    model: 'string',
    miles: {type: 'int', default: 0},
  }
};
const PersonSchema = {
  name: 'Person',
  properties: {
    name:     'string',
    birthday: 'date',
    cars:     'Car[]'
    picture:  'data?', // optional property
  }
};

Now the questions...

1) How do i get list of persons who own a specific car from the above given schema ?

2) Should i give a property to Car schema, like owner: 'Person' ? or is there any reverse relation thing. (I don't know the perfect term, I am a newbie :/ )

NOTE: Further questions can be asked in comments.


Solution

  • Yes there are inverse relations to be defined. For that you should create schema like this,

    const CarSchema = { 
      name: 'Car', 
      properties: { 
        make: 'string', 
        model: 'string', 
        miles: {type: 'int', default: 0}, 
        owner: 'Person'
      } 
    }; 
    const PersonSchema = {
      name: 'Person', 
      properties: { 
        name: 'string', 
        birthday: 'date', 
        cars: {type: 'linkingObjects', objectType: 'Car', property: 'owner'}
        picture: 'data?' 
      } 
    };
    

    Here, Person has cars where the owner property in Car object is mapped to this person. car.owner gives you the Person object and person.cars give you all the cars that person owns.