Decoding a BSON array to SwiftUI Object

Hello all - I’m relatively new to the Mongo platform and I have a question about decoding data.

My current setup is a SwiftUI app using a MongoDB Realm that is connected to Atlas. Rather than go through the setup for a second Realm to access public data (the app’s realm is partitioned for the logged in user), I’m creating functions in the realm to be called from the app to return public data (lists of events, places, etc.).

I have the function working, returning something like this:

const query = { "_id": BSON.ObjectId(eventId) }
const events = cluster.db("myDatabase").collection("Events");
  let foundEvents = events.find(query)  
    .sort({ name: 1 })

This returns a value to my app, which is rather complex:

           "attribute1": Optional(RealmSwift.AnyBSON.objectId(xyz)), 
           "attribute2": Optional(RealmSwift.AnyBSON.objectId(yzx)), 
           "attribute3": Optional(RealmSwift.AnyBSON.string("myObjName")), 
           "__v": Optional(RealmSwift.AnyBSON.int32(0))

I have the model defined in my Swift project, for the document type. Thats what is being used for the Realm Sync communications. Is there a way to convert this BSON abomination to my object type?
I can get to a specific attribute with ugly code like this:
let attribute1Value = (result.arrayValue?[0]?.documentValue?["attribute1"] as? AnyBSON)?.stringValue ?? "No Value"
But it feels like there must be a better way

Looking for any and and all help, thanks in advance.

1 Like

Were you able to find a clean solution to this? I am also having trouble transforming the returning object into a Swift Class

No, I ended up implementing and opening a second public realm for data that is not user specific.