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
相关产品推荐
相关产品推荐

