Lookup by primaryKey returns nil

I store my companyId in the custom user data class, User.
Upon login I want to retrieve the company object and so I first get the User’s custom data with companyId and then the lookup. I have tripled checked they keys, override primaryKy on _id, review the atlas data and the key is correct.

I don’t see that lookup in the log file as I presume it is local so I don’t know what is wrong in the lookup.

Frustrated at the pace of learning the simplest things.

func getCompany() {
app.login(credentials: Credentials.jwt(token: CredentialToken.jwtToken)) { (result) in
switch result {
case .failure(let error):
print(“Failed to log in: (error.localizedDescription)”)
case .success(let user):
// If the user data has been refreshed recently, you can access the
// custom user data directly on the user object
print(“User custom data: (user.customData)”)
// Refresh the custom user data
user.refreshCustomData { (result) in
switch result {
case .failure(let error):
print(“Failed to refresh custom data: (error.localizedDescription)”)
case .success(let customData):
print(“CompanyID: (customData[“companyId”] ?? “company ID not set”)”)
self.companyId = customData[“companyId”] as? ObjectId
let configuration = user.configuration(partitionValue: user.id)
let realm = try! Realm(configuration: configuration)

                        //self.companyId is correct and in the company atlas collection.

                        let companyToOpen = realm.object(ofType: Company.self, forPrimaryKey:  self.companyId)
                        print (companyToOpen) <=== always nil
                        return
                    }
                }
        }
    }
}
1 Like