How to sync relationships in realm flexible sync

I’m using realm flexible sync and I don’t know how to solve the following problem:

My app consists of the following domain architecture:

  • a user can have many books
  • a book can have multiple pages
  • a page can have multiple paragraphs

The models would look like this:

class Book: Object, ObjectKeyIdentifiable {
    @Persisted(primaryKey: true) var _id: UUID
    @Persisted var name: String
    @Persisted var pages = List<Page>()
    @Persisted var ownerId = ""

class Page: Object, ObjectKeyIdentifiable {
    @Persisted(primaryKey: true) var _id: UUID
    @Persisted var label: String
    @Persisted var paragraphs = List<Paragraph>()

class Paragraph: Object, ObjectKeyIdentifiable {
    @Persisted(primaryKey: true) var _id: UUID
    @Persisted var text: String

When opening the realm, I subscribe to each of those collections and have defined a role at the atlas backend so every user is allowed to read and write documents where the ownerId is identical to there userId.

No I’m wondering how to deal with the related collections. I think it’s not necessary to define the ownerId there as well, because they’re not accessed on their own and just accessible via their parent, at least in the UI. But I think that wouldn’t work considering the defined backend role because there’s no ownerId present.

Can someone help me out?

Hello @Andreas_Teich ,

Welcome to the MongoDB Community :wave:

You may not need to have separate collections for book, pages, and paragraphs. They could be embedded objects in your book collection.

When you subscribe to the queryable fields and perform the query, the embedded objects will be downloaded. Please follow the embedded object section in the documentation.

I hope provided information is helpful.


Many thanks. I already considered that, but from my point of view, pages could get massive and I don‘t want to produce a massive array anti pattern with that. So I would like to solve that problem using relationships :confused:

Would you have any suggestions here as well?

Hi @Andreas_Teich ,

If I understood you correctly, you have subscribed to separate collections already. You may need to have some id to connect all collections.
The defined backend role with ownderid is an example to show how the rules can be defined. You are free to change them as per your requirements.

You can define roles and permissions to allow documents you need. You can read more on roles in the documentation.

I hope provided information is helpful.

henna :performing_arts: