I have a person that has a related collection of “tags”. Each person can have multiple tags.
I’ve found the relationship CRUD section of the docs, but it skips the part that says how to actually write the code to connect two documents.
Here is a simplified version of my People schema.
export class People extends Realm.Object<People> {
_id!: string;
name: string;
email?: string;
tags?: Realm.List<Tags>;
org_id!: string;
static schema: Realm.ObjectSchema = {
primaryKey: '_id',
name: 'people',
properties: {
_id: {
type: 'string',
default: () => new Realm.BSON.ObjectID().toHexString(),
},
name: 'string',
email: 'string?',
createdAt: { type: 'date', default: () => new Date() },
tags: 'tags[]',
org_id: 'string',
},
};
}
And here is my Tags model
export class Tags extends Realm.Object<Tags> {
_id!: string;
name: string;
org_id: string;
static schema: Realm.ObjectSchema = {
primaryKey: '_id',
name: 'tags',
properties: {
_id: {
type: 'string',
},
name: 'string',
is_active: { type: 'bool', default: true },
org_id: 'string',
},
};
}
Here is my code for adding a new person with one tag.
const person = realm.write(() => {
return new People(realm, {
email,
name,
org_id: org._id,
tags: [{ name: '2021', _id: `${org._id}-2021` }],
});
});
I get the error "Exception in HostFunction: Attempting to create an object of type ‘tags’ with an existing primary key value ‘‘id123-2021’’
This is happening because realm is trying to create this same tag that already exists in the DB. Instead of creating it I need to connect the two. How do I do that?
Cross posted here as well