如何在IndexedDB中定义包含数组字段的自定义对象存储表?
IndexedDB 自定义嵌套文档结构配置方案
IndexedDB 原生支持嵌套的对象/数组结构,无需额外做特殊序列化处理,针对你当前使用的类ngx-indexed-db库的配置格式,有两种实现方案可选:
方案一:直接嵌套存储(最常用,适合小体量关联数据)
直接把lists字段作为people对象存储的普通字段配置即可,IndexedDB会自动序列化存储整个LookUp数组,无需单独建表。
修改后的dbConfig代码如下:
const dbConfig: DBConfig = { name: 'MyDb', version: 1, objectStoresMeta: [{ store: 'people', storeConfig: { keyPath: 'id', autoIncrement: true }, storeSchema: [ { name: 'name', keypath: 'name', options: { unique: false } }, // 直接添加lists字段配置即可,不需要额外标记数组类型 { name: 'lists', keypath: 'lists', options: { unique: false } } ] }] };
后续读写操作时直接传入完整的People实例即可,LookUp数组会完整存在对应条目里,读取时直接取lists属性就能拿到完整的数组结构。
方案二:关联独立表存储(适合LookUp数据需要复用、体量较大的场景)
如果你的LookUp数据需要被多个People实例复用,不想冗余存储,可以单独为LookUp建对象存储,people表的lists只存LookUp的id数组,查询时再关联取数据:
const dbConfig: DBConfig = { name: 'MyDb', version: 1, objectStoresMeta: [ { store: 'people', storeConfig: { keyPath: 'id', autoIncrement: true }, storeSchema: [ { name: 'name', keypath: 'name', options: { unique: false } }, // 这里存储的是LookUp的id数组 { name: 'lists', keypath: 'lists', options: { unique: false } } ] }, // 新增lookUp独立对象存储 { store: 'lookUp', storeConfig: { keyPath: 'id', autoIncrement: true }, storeSchema: [ { name: 'name', keypath: 'name', options: { unique: false } } ] } ] };
内容的提问来源于stack exchange,提问作者Harshad Pansuriya
相关产品推荐
相关产品推荐

