【问题标题】:React Native realm get objects return array without valuesReact Native领域获取对象返回没有值的数组
【发布时间】:2020-10-20 00:32:59
【问题描述】:

领域反应原生返回的对象数组没有值。

package.json中的包版本

"react": "16.11.0",
"react-native": "0.62.2",
"realm": "^6.0.2"

节点版本:v12.17.0

react-native-cli:2.0.1

定义Students类和架构如下:

export class Students {}

Students.schema = {
  name: 'students',
  primaryKey: 'roll_no',
  properties: {
    name: {type: 'string'},
    roll_no: {type: 'string'},
    order: {type: 'int', default: 0},
  },
};

全局创建领域数据库对象:

export const realmDatabase = new Realm({
  schema: [Students],
  path: 'school.realm',
  schemaVersion: 1,
});

使用下面的函数将数据插入到student 表中

export function insertStudents(students) {
    realmDatabase.write(() => {
      students.forEach((student) => {
        try {
          realmDatabase.create('students', {
            name: student['name'],
            order: student['order'],
            roll_no: student['roll_no'],
          });
        } catch (error) {}
      });
    });
}

使用以下函数从数据库中获取学生,但它检索的是空的对象数组

export function getStudents() {
  try {
    let students = realmDatabase.objects('students');
    console.log(students);
  } catch (error) {}
}

输出:

{ '0': {},
  '1': {},
  '2': {},
  '3': {},
  '4': {},
  '5': {},
  '6': {}}

【问题讨论】:

    标签: react-native realm


    【解决方案1】:

    终于解决了这个问题,之前我的对象模型是class 类型,并且在旧版本的领域上运行良好,但现在它不适用于我更新版本的realm,需要将其更改为:

    在旧版本中,模型对象如下:

    export class Students {}
    
    Students.schema = {
      name: 'students',
      primaryKey: 'roll_no',
      properties: {
        name: {type: 'string'},
        roll_no: {type: 'string'},
        order: {type: 'int', default: 0},
      },
    };
    

    更新版本:

    export const Students = {
          name: 'students',
          primaryKey: 'roll_no',
          properties: {
            name: {type: 'string'},
            roll_no: {type: 'string'},
            order: {type: 'int', default: 0},
          },
        };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多