I’m working in React Native and have a schema which utilizes a relationship as outlined here. My question is: when I create a new instance of my schema inside realm using realm.create
, do I need to pass the entire related object to the constructor utilized by realm.create
? This seems a bit strange, I would think that I could pass an ObjectId to the constructor, but I have not been able to get that to work (I get an error tell me it’s missing properties, eg the other properties on the schema of the related object). Is the correct / only way to create an object which is related to another to pass the entire related object? Here is my schema:
import { Realm } from '@realm/react'
import { User } from './User'
export class Activity extends Realm.Object<Activity, 'createdBy' | 'name'> {
_id: Realm.BSON.ObjectId = new Realm.BSON.ObjectId()
version: Realm.Types.Int = 3
createdAt: Date = new Date()
createdBy!: User
name!: string
aliases!: Realm.List<string>
static primaryKey = '_id'
constructor(realm: Realm, name: string, createdBy: User) {
super(realm, { name, createdBy, aliases: [] })
}
static generate(createdBy: User, name: string = '') {
return {
_id: new Realm.BSON.ObjectId(),
version: 3,
createdAt: new Date(),
createdBy,
name,
aliases: []
}
}
}
and the function used to create a new Activity:
const handleCreateActivity = useCallback(() => {
if (!user?._id) {
console.error('Missing user.id in call to handleCreateActivity')
return
}
realm.write(() => {
// The following worked:
realm.create('Activity', Activity.generate(user, activityName))
})
}, [user?._id, realm])
where user
is the entire User
object that I want to relate to this new instance of an Activity
object.
A couple side notes:
- I’m still not clear on what the role of the constructor inside the class definition plays in Realm. It could be incorrect / superfluous. I’m calling
generate
rather than the constructor in my example. - I tried changing around my types to have generate accept a Realm.BSON.ObjectId, this is when I get a “Error: Exception in HostFunction: Missing value for property …” asking for the missing properties from the referenced schema.
Thanks!