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

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 Dog objects in the database that belongs 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.

Good question!

Conceptually, if a Person is instantiated in code, and then some dogs, and then the dogs are added to the Persons dogs property, when the Person is written to Realm within a write transaction, the dogs will be too! How cool is that?

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 also also be written.

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.

Does that help?

1 Like

Yes, very clear. I will try it and let you know on stackoverflow.
Thanks a million.
I have 2 or 3 open issues here if you have time like this one. and that one

PS: I wish MongoDB could provide a fully working one-to-many React Native example out of the box, but for some reasons, its not the case.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.