Search code examples
react-nativerealmone-to-many

React Native MongoDB Realm - How to create a object in a One-to-Many Relationship?


I am working on React Native MongoDB Realm database.

The doc explains how to create a One-to-Many Relationship schema as shown below:

const Person = {
  name: "Person",
  properties: {
    name: "string",
    birthdate: "date",
    dogs: "Dog[]"
  }
};

const Dog = {
  name: "Dog",
  properties: {
    name: "string",
    age: "int",
    breed: "string?"
  }
};

But I dont see where it explains how to add in the database Dog objects that belong to a person. A Person should be specified in some way.

I am using Realm React, so the dog creation code looks something like :

person1: Person =  ...

realm.write(() => {
   return  new Dog(realm, dogFields);
});

If I have a person1 already in the DB, how to modify this code so that person1 becomes the owner of this newly created dog.


Solution

  • A good conceptual question and I think this can be addressed at a high level.

    Start with some pseudo code for a Person Object with a name and a list of dogs and a Dog object.

    Person {
      name = ""
      dogs = List of dogs
    }
    
    Dog {
      name = ""
    }
    

    Conceptually, if a Person is instantiated in code

    let p = Person()
    

    and then a dog

    let d = Dog()
    

    and then the dog is added to the Persons dogs property,

    p.dogs.add(d)
    

    when the Person is written to Realm within a write transaction, the dogs will be too! How cool is that?

    realm.write {
       realm.add(p) //the person and its dog is added; both objects are written
    }
    

    Another example is if there’s in existing person that’s already been written. When it’s read in and new dogs are added to the person (within a write transaction), they will be added to the persons list and also be written as separate objects

    Lastly, if there are Person and Dogs that have already been written, if a person is read in, and then a dog is read in, when the dog is added the Person Dog property within a write transaction, it will just update the person since the dog already exists.