Migrating to new Realm Database

We had a production database that was compromised and need to move users to a new database. How can we take a current users, who is authenticated and connected to old Realm database, and sync their data with the new database?

I have tried following the following recommendations, but haven’t had success.

So if anyone else runs into this question/issue, here is what I did to resolve it:

  1. Check to see if the user’s current Realm is not the same as the Realm you would like them to be in.
    if (!currentRealmInstance.syncSession.url.startsWith(desiredRealmURL))

  2. If not, logged the user into the new Realm server. We use JWT, so this involved creating the credentials then logging in.
    const user = await Realm.Sync.User.login(ServerURL, credentials);

  3. Opened a new instance of Realm with this user.
    const newRealm = new Realm(realmConfig);. We also are keeping a reference of the old Realm.

  4. Copy the data over into the new Realm. We used an array of the Realm schema objects we wanted to copy over. In this code example it is just the User data.

const promises = ['User'].map(obj =>
  const data = oldRealm.objects(schema);
  if (data.length) {
    data.forEach(el => {
      newRealm.write(() => {
        newRealm.create(schema, el, 'modified');
      });
    });
  }
);
  1. After all the data has copied over we saved the Realm instance.
Promise.all(promises)
  .then(async () => {
    return dispatch({
      type: 'set_realm_connection',
      payload: newRealm,
    });
})
  1. Since we are using Redux, we refreshed our reducers with the copied data.

Here’s the data on the frontend that we used to open the app or wait until the current Realm URL equals the desired Realm URL.

  checkRealmInstance = setInterval(async () => {
    const {realm} = this.props;
    if (!Realm.Sync.User.current) {
      clearInterval(this.checkExist); // Don't perform checks if user isn't logged into Realm
    } else if (realm.syncSession.url && !realm.syncSession.url.startsWith(RealmURL)) {
      await this.props.getUserData(); // Loads data from current (old) Realm
      this.props.updateSpinnerVisibility(true, 'Updating Profile');
      this.props.copyDataToNewRealm();
    } else if (realm.syncSession.url && realm.syncSession.url.startsWith(RealmURL)) {
      clearInterval(this.checkExist);
      this.props.updateSpinnerVisibility(false);
      await this.props.getUserData(); // Retrieves new data and places in Redux
      this.props.navigation.navigate('App');
    } else {
      console.log('.'); // Waiting for initial Realm to load
    }
  }, 100);

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