React Native Realm Get对象返回没有值的数组

时间:2020-06-29 19:02:39

标签: react-native realm

Realm对没有值的对象的本机返回数组进行反应。

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': {}}

1 个答案:

答案 0 :(得分:0)

终于解决了这个问题,较早的是我的对象模型是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},
      },
    };