Setting the user_id/owner_id field of a document server-side

My approach is to let userId be an empty string if there are no users.

class Item: Object, ObjectKeyIdentifiable {
    @Persisted(primaryKey: true) var _id: ObjectId
    @Persisted var userId: String
    @Persisted var name: String
    
    convenience init(name: String, userId: String? = nil) {
        self.init()
        self.name = name
        if let userId = userId {
            self.userId = userId
        }
    }
}

I change the configuration environment depending on whether there is a logged in user.

struct ContentView: View {
    
    @ObservedObject var app = Realm.app
    
    var body: some View {
        if let config = app.createFlexibleConfiguration() {
            MainScreenSync()
                .environment(\.realmConfiguration, config)
                .environmentObject(app)
        } else {
            MainScreen()
                .environmentObject(app)
        }
    }
}

Then, I rely on the SwiftUI syntax to easily access the synced realm.

struct MainScreenSync: View{
    @EnvironmentObject var app: RealmSwift.App
    //    @Environment(\.realm) var syncedRealm
    @ObservedResults(Item.self) var syncedItems
    
    var body: some View {
        VStack {
            MainScreen()
            Text(app.currentUser?.description ?? "not logged in")
        }
        .onAppear {
            if let localRealm = try? Realm(), let user = app.currentUser {
                let localItems = localRealm.objects(Item.self)
                for item in localItems {
                    // local -> synced
                    let syncedItem = Item(value: item)
                    syncedItem.userId = user.id
                    $syncedItems.append(syncedItem)
                    // delete local
                    try? localRealm.write {
                        localRealm.delete(item)
                    }
                }
            }
        }
    }
}

Full code