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 {
            guard error == nil else {
                print("Signup failed: \(error!)")
                self!.errorLabel.text = "Signup failed: \(error!.localizedDescription)"
            print("Signup successful!")
            self!.errorLabel.text = "Signup successful! Signing in..."

func login(){
app.login(credentials: Credentials.emailPassword(email: email!, password: password!)) { result in
    DispatchQueue.main.async {
        switch result {
        case .failure(let error):
            print("Login failed: \(error)")
            self.errorLabel.text = "Login failed: \(error.localizedDescription)"
        case .success(let user):
            print("Login succeeded!")
            var configuration = user.configuration(partitionValue: "user=\(")
            configuration.objectTypes = RealmManager.OBJECT_TYPES
            Realm.asyncOpen(configuration: configuration) { [weak self](result) in
                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?.goToViewController(storyboardID: "Main", viewcontrollerID: "home")
                            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 {
        errorLabel.text = ""
    } else {
    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 ="mongodb-atlas");
const users = cluster.db("mseasedb").collection("User");
return users.insertOne({
  _partition: `user=${}`,
  profilePicture: null,
  hasSignedConsent: false,
  gender: '',
  birthday: '',
  typeOfMS: '',
  diagnosisDate: '',
  treatmentBeginningDate: '',
  mascot: 'Drummer',
  canReadPartitions: [`user=${}`],
  canWritePartitions: [`user=${}`],

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.