如何在realm数据库中检索react-native中的nameKey-value?

时间:2016-03-13 21:50:31

标签: database react-native realm

我需要一个反应原生的Android / iOS应用程序的数据库。作为学习领域的第一步,我想用领域替换AsyncStorage来读取应用程序设置。

  1. 问题:nameKey访问值的语法是什么?
  2. 我的AppSetting架构将名称设置为主键:

    const AppSetting = {
      name: 'AppSetting',
      primaryKey: 'name',
      schemaVersion: 1,
      properties: {
        name:   {type: 'string'},
        value:   {type: 'string'},
      }
    };
    

    如果appSettings为空,那么我写AppSettingsDefault:

    const AppSettingsDefault = [
      {
        name: 'version',
        value: '0,'
      },
      {
        name: 'gpsEnabled',
        value: 'true,'
      },
      {
        name: 'unitType',
        value: '2,'
      },
    ];
    console.log('appSettings.length:', appSettings.length);
    if(0 >= appSettings.length) {
      console.log("Init default: AppSetting when app is run first time");
      for(let i = 0; i < AppSettingsDefault.length; ++i) {
        let name = AppSettingsDefault[i].name;
        let value = AppSettingsDefault[i].value;
        console.log(name, '=', value);
        realm.write(()=>{
          realm.create('AppSetting', {
            name: name,
            value: value,
          });
        })
      }
    }
    

    在react-native中检索'gpsEnabled'值的领域语法是什么?

    let realm = new Realm({schema:
      [AppSetting], schemaVersion: 1});
    let appSettings = realm.objects('AppSetting');
    // How to retrieve a value by the primary key?
    console.log('gpsEnabled', appSettings['gpsEnabled'];  <- This does NOT work
    

    提前感谢任何提示或方向,

1 个答案:

答案 0 :(得分:2)

试试这个

 let result = realm.objects('AppSetting').filtered('name = "gpsEnabled"');
 let val = result[0].value;

https://realm.io/docs/react-native/latest/#queries