Realm doesn't contain user after registeration

I’m developing a swift application using mongodb+realm. In my signup function, sometimes when the realm is returned it does not contain any users (but the created user is showing in the cluster). So I get a nil exception in hasSignedConsent. Am I missing something?

func signup() {
app.emailPasswordAuth.registerUser(email: email!, password: password!, completion: { [weak self](error) in
        DispatchQueue.main.async {
            self!.setLoading(false)
            guard error == nil else {
                print("Signup failed: \(error!)")
                self!.errorLabel.text = "Signup failed: \(error!.localizedDescription)"
                return
            }
            print("Signup successful!")
            self!.errorLabel.text = "Signup successful! Signing in..."
            self!.login()
        }
    })
}

func login(){
setLoading(true)
app.login(credentials: Credentials.emailPassword(email: email!, password: password!)) { result in
    DispatchQueue.main.async {
        self.setLoading(false)
        switch result {
        case .failure(let error):
            print("Login failed: \(error)")
            self.errorLabel.text = "Login failed: \(error.localizedDescription)"
            return
        case .success(let user):
            print("Login succeeded!")
            self.setLoading(true)
            var configuration = user.configuration(partitionValue: "user=\(user.id)")
            configuration.objectTypes = RealmManager.OBJECT_TYPES
            Realm.asyncOpen(configuration: configuration) { [weak self](result) in
                self!.setLoading(false)
                switch result {
                case .failure(let error):
                    fatalError("Failed to open realm: \(error)")
                case .success(let userRealm):
                    RealmManager.shared.setRealm(realm: userRealm, handler:{
                        if RealmManager.shared.hasSignedConsent(realmA: userRealm){
                            self?.scheduleReminders()
                            self?.goToViewController(storyboardID: "Main", viewcontrollerID: "home")
                        }
                        else{
                            self?.goToViewController(storyboardID: "Onboarding", viewcontrollerID: "consentVC")
                        }
                    })    
                }
            }
        }
    }
}

func hasSignedConsent(realmA: Realm) -> Bool {
    let user = realmA.objects(User.self).first
    return user!.hasSignedConsent
}

func setLoading(_ loading: Bool) {
    activityIndicator.isHidden = !loading
    if loading {
        activityIndicator.startAnimating()
        errorLabel.text = ""
    } else {
        activityIndicator.stopAnimating()
    }
    emailTextField.isEnabled = !loading
    passwordTextField.isEnabled = !loading
    signupLoginButton.isEnabled = !loading
}

here is my trigger that is fired when a new user is added:

and here is the createNewUserDocument function:

exports = async function createNewUserDocument({user}){
const cluster = context.services.get("mongodb-atlas");
const users = cluster.db("mseasedb").collection("User");
return users.insertOne({
  _id: user.id,
  _partition: `user=${user.id}`,
  name: user.data.email,
  profilePicture: null,
  hasSignedConsent: false,
  gender: '',
  birthday: '',
  typeOfMS: '',
  diagnosisDate: '',
  treatmentBeginningDate: '',
  mascot: 'Drummer',
  canReadPartitions: [`user=${user.id}`],
  canWritePartitions: [`user=${user.id}`],
  });
};

Also, whenever this problem happens logs show:
“Client bootstrap completed in … . Received 1 download(s) containing 1 changeset(s) …” instead of 2 changesets which should normally happen.

Hi @Negar_Haghbin — welcome to the community forum!

Your trigger should fire when you login, but it’s asynchronous. If you open the realm immediately after logging in, the trigger may or may not have run yet and so the user object may or may not be there yet. So, you should (probably) treat the realm being empty as meaning that they haven’t yet signed consent.

1 Like

Hi Andrew,
Thank you for your response!
I can treat the realm being empty and show the consent page, however at some point I need to update some fields of the user object (birthday, gender,…). Should I add another collection for those fields or is there an easier way to make sure that the user object is added? (I’ve tried adding sleep() but it didn’t work)
What do you suggest?

You should be able to observe the realm and only present the profile page once the new user doc has synced to the app. Alternatively, you could create the user doc in Realm rather than creating it in a Realm function.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.