3

我在我的 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);
    }
4

2 回答 2

1
const OpenRealmBehaviorConfiguration = {
    type: "openImmediately",
}

const configuration = {
    schema: [UserSchema],
    sync: {
        user: app.currentUser,
        partitionValue: "user_1",
        // Add this two lines below
        newRealmFileBehavior: OpenRealmBehaviorConfiguration,
        existingRealmFileBehavior: OpenRealmBehaviorConfiguration,
    }
}
于 2021-06-21T16:21:10.377 回答
0

我在这里找到了类似问题的答案:https://developer.mongodb.com/community/forums/t/open-synced-local-database-when-completely-offline/11169/2 您可以执行以下操作:

async function getRealm() {
    const app = new Realm.App("your-app-id");
    if (app.currentUser) {
        // A user had already logged in - open the Realm synchronously
        return new Realm(getConfig(app.currentUser));
    }

    // We don't have a user - login a user and open the realm async
    const user = await app.logIn(Realm.Credentials.anonymous());
    return await Realm.open(getConfig(user));
}

function getConfig(user) {
    return {
        sync: {
            user,
            partitionValue: "my-partition"
        }
    };
}
于 2020-11-09T20:51:48.933 回答