How to handle flexible data models

I have an app where a few documents will not have a fixed schema. That is, say I have a project document and in my project a user can add sections to the document. So, maybe:

  • Project, just one root node
  • Project / Servers, here I may have several server objects I need to add
  • Project / Servers / OS, here I might have dozens of different types of OS’s that I will track all with different fields of different types

Is this possible to do with Realm? I know it supports the more simple case where I know exactly the structure of an object ahead of time. But, what if I don’t know the structure ahead of time?

My app is pretty large and will have hundreds of these types sub-documents (nested objects say within a Project document) where the schema / structure will be highly dynamic. In fact, a high degree of my data will have a structure that changes frequently.

I’m hoping I can still use Realm to just sync/upload/download whatever I hand it. But, looking through the docs I’m not so sure.

Thanks!

There are many ways you can choose to model a structure like that. Usually the easiest way will be to add a dictionary to the objects so it can have extra unstructured values. You could do something like this (in Swift, but you could do this in any of the SDK’s):

class Project: Object {
    @Persisted(primaryKey: true) var _id: ObjectId
    @Persisted var name = ""
    @Persisted var servers: MutableSet<Servers>
}

class Servers: Object {
    @Persisted(primaryKey: true) var _id: ObjectId
    @Persisted var name = ""
    @Persisted var os: OS?
    @Persisted var properties: Map<String, AnyRealmValue>
}

class OS: Object {
    @Persisted(primaryKey: true) var _id: ObjectId
    @Persisted var name = ""
    @Persisted var properties: Map<String, AnyRealmValue>
}
1 Like

Ok that makes sense. Glad to hear and so far I’m just basically in love with Realm for my app so I’m glad this use case can work.

Alright, off I go…