首页 > 解决方案 > 如何在完全离线时使用 MongoDB Synced Realm 数据库的本地副本?

问题描述

我在我的 React Native 应用程序上使用 MongoDB Realm Sync。当我在线启动我的应用程序并随后断开互联网连接时,我的领域工作正常。我可以看到我的数据,也可以在我重新上线时写入与服务器同步的数据。但是当我完全离线启动我的应用程序时,我的应用程序不显示任何数据。据我了解,即使应用程序完全离线启动,领域也应该读取本地数据库并返回数据。不是吗?当我离线启动我的应用程序时如何访问我的数据?下面是我用来与服务器同步的代码。

const config = {
      schema: [sessionSchema],
      sync: {
        user,
        partitionValue: 'Test',
      },
    };

try {
      Realm.open(config)
        .then((openedRealm) => {
          if (canceled) {
            openedRealm.close();
            return;
          }
          realmRef.current = openedRealm;
          const syncSessions = openedRealm.objects('session');

         openedRealm.addListener('change', () => {
            setSessions([...syncSessions]);
         });
        setSessions([...syncSessions]);
     }
  } catch (e) {
      console.log('ERROR', e);
    }

标签: react-nativerealmmongodb-realm

解决方案


const OpenRealmBehaviorConfiguration = {
    type: "openImmediately",
}

const configuration = {
    schema: [UserSchema],
    sync: {
        user: app.currentUser,
        partitionValue: "user_1",
        // Add this two lines below
        newRealmFileBehavior: OpenRealmBehaviorConfiguration,
        existingRealmFileBehavior: OpenRealmBehaviorConfiguration,
    }
}

推荐阅读