You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native Realm中存储对象数组的正确Schema数据类型是什么

问题解答

Realm存储对象数组有两种实现方案,根据你的业务场景选择即可:


方案1:固定结构对象数组(推荐)

你示例中的数组内对象结构固定,优先定义独立子Schema约束字段类型,相比mixed类型读写性能更高,同时支持类型校验和子字段查询。

// 定义数组内部对象的子Schema
const ArrayItemSchema = {
  name: "ArrayItem",
  properties: {
    key1: "int",
    key2: "int",
    key3: "int"
  }
}

// 主Schema定义
const mySchema = {
  name: "mySchema",
  properties: {
    _id: "objectId",
    arrOfObj: "ArrayItem[]" // 格式为「子Schema名称+[]」表示该类型的对象数组
  }
}

// 插入数据示例
realm.write(() => {
  realm.create("mySchema", {
    _id: new Realm.BSON.ObjectId(),
    arrOfObj: [{ key1: 1111, key2: 2222, key3: 333 }]
  })
})

方案2:任意结构对象数组(仅结构不固定时使用)

如果数组内的对象没有固定结构,可以使用mixed[]类型定义。你之前遇到的报错是因为插入数据时给arrOfObj字段传入了单个对象,而非数组格式,修正插入格式即可:

const mySchema = {
  name: "mySchema",
  properties: {
    _id: "objectId",
    arrOfObj: "mixed[]" // 明确声明为mixed类型数组
  }
}

// 插入数据示例
realm.write(() => {
  realm.create("mySchema", {
    _id: new Realm.BSON.ObjectId(),
    // 错误写法:arrOfObj: { key1: 1111, key2: 2222, key3: 333 }
    // 正确写法:必须传入数组格式,哪怕只有一个元素
    arrOfObj: [{ key1: 1111, key2: 2222, key3: 333 }]
  })
})

内容的提问来源于stack exchange,提问作者Amani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 19:45:01