Realm 文件上传,无法在 React Native 中处理其中的数据(无 Realm 导出和导入)

问题描述 投票:0回答:1

没有官方方法可以导出或导入领域数据。我可以下载 .realm 文件,但无法从中检索数据。

这是导出功能

import Realm from 'realm';
import RNFS from 'react-native-fs';
import {getRealm} from './realmService';

export const exportRealmData = async () => {
  try {
    const realm: Realm = await getRealm();
    const exportFileName = 'qqqq.realm';
    const exportFilePath = `${RNFS.DocumentDirectoryPath}/${exportFileName}`;

    if (await RNFS.exists(exportFilePath)) {
      await RNFS.unlink(exportFilePath);
    }

    const config = {
      path: exportFilePath,
      schema: realm.schema,
      schemaVersion: realm.schemaVersion + 1,
      encryptionKey: realm.encryptionKey,
    };

    realm.writeCopyTo(config);

    const downloadsFolder = RNFS.DownloadDirectoryPath;
    const destinationFilePath = `${downloadsFolder}/${exportFileName}`;

    await RNFS.moveFile(exportFilePath, destinationFilePath);

    console.log('Realm data exported to', destinationFilePath);
    return destinationFilePath;
  } catch (error) {
    console.error('Error exporting Realm data', error);
  }
};

我尝试上传和检索数据,但我无法做到这一点

  function normalizePath(path: string | undefined) {
    try {
      if (path === undefined) {
        throw console.error('undefined');
      }
      if (Platform.OS === 'ios' || Platform.OS === 'android') {
        const filePrefix = 'file:';
        if (path.startsWith(filePrefix)) {
          path = path.substring(filePrefix.length);
        }
        path = decodeURIComponent(path);
        return path;
      }
    } catch (e) {
      console.error({msg: 'Failed to normalize path', data: e});
    }
  }

  const handleFilePick = async () => {
    try {
      const result = await DocumentPicker.pick({
        type: [DocumentPicker.types.allFiles],
      });
      console.log(result);
      const {0: file1} = result;

      const path = normalizePath(file1?.uri);
      console.log(path);
      setRealmFile(path);
    } catch (err) {
      console.error(err);
    }
  };

  console.log(realmFile);

  const handleDataSubmit = async () => {
    try {
      if (!realmFile) {
        console.error('Please upload a .realm file');
        return;
      }

      const realm = await getRealm();
      const existingRealm = await Realm.open({path: realmFile.uri});

      console.log('This is the existing realm:', existingRealm);

      realm.write(() => {
        [User, Category, Expense, Currency, Debtor, Debt].forEach(schema => {
          const objects = existingRealm.objects(schema.schema.name);
          console.log(`Data for ${schema.schema.name}:`, objects.toJSON());

          objects.forEach(object => {
            realm.create(schema.schema.name, object, Realm.UpdateMode.Modified);
          });
        });
      });

      await AsyncStorageService.setItem('isOnboarded', JSON.stringify(true));
      dispatch(setIsOnboarded(true));

      console.log('Data updated successfully!');
    } catch (error) {
      console.error('Error updating data:', error);
    }
  };

这是日志

 LOG  content://com.android.providers.downloads.documents/document/msf:1000000035
 LOG  [{"fileCopyUri": null, "name": "qqqq.realm", "size": 4848, "type": "application/octet-stream", "uri": "content://com.android.providers.downloads.documents/document/msf%3A1000000035"}]
 LOG  content://com.android.providers.downloads.documents/document/msf:1000000035
 LOG  This is the existing realm: {"beforeNotifyListeners": {"eventType": "beforenotify", "listeners": Set {}, "realm": [Circular]}, "changeListeners": {"eventType": "change", "listeners": Set {}, "realm": [Circular]}, "schemaExtras": {}, "schemaListeners": {"eventType": "schema", "listeners": Set {}, "realm": [Circular]}, "syncSession": null}

帮助我从 React Native 中的 .realm 文件中检索数据

android reactjs mongodb react-native realm
1个回答
0
投票

没有官方方法可以导出或导入领域数据

Realm Studio既可以导入也可以导出数据。

您还可以使用 mongoexport 命令行工具。该命令将您的集合转储到包含 JSON 数据的平面文件。

mongoexport 命令已记录在此处

MongoDB 大学中还有一个视频,从管理员角度介绍了导出

第三种选择是使用 SDK 编写一些快速代码,将数据转储到文件中 - 应该大约 15 行代码。

此外 - 如果您登录 MongoDB 控制台并转到顶部的数据服务,则可能会选择集合选项卡。选择 Cmd Line Tools 选项卡,然后向下大约 1/2 有一个用于数据导入和导出工具的完整部分

© www.soinside.com 2019 - 2024. All rights reserved.