Kotlin中Realm关联Atlas插入对象:一对多关联不显示问题排查
Realm一对多关联同步Atlas失败问题解决
问题核心
你创建的Category与Product一对多关联未在Atlas中正确同步,表现为Product的category字段缺失、Category的products列表无关联数据,问题出在Realm对象关联注解缺失、Atlas关系配置错误、数据插入时未维护双向关联这三个环节。
修复步骤
1. 修正Realm对象的关联注解
Realm的双向一对多关联需要显式标注反向关联,在Product类的category字段添加@Inverse注解,指定关联Category类中的products字段,让Realm自动维护双向关联:
class Category: RealmObject { @PrimaryKey var _id: ObjectId = ObjectId.create() var name: String = "" var image: String = "" var products: RealmList<Product> = realmListOf<Product>() var company_id: Company? = null } class Product: RealmObject { @PrimaryKey var _id: ObjectId = ObjectId.create() var name: String? = null var quantity: Int? = null var price: Float? = null var image: String? = null var shortDescritpion: String? = null var longDescritpion: String? = null var barcode: Long? = null // 添加@Inverse注解,关联Category的products字段 @Inverse(field = "products") var category: Category? = null }
2. 修正Atlas的Category关系配置
当前Category的products关系中foreignKey配置错误,应指向Product类中存储Category外键的category字段,而非_id。修改后的关系配置如下:
{ "products": { "ref": "#/relationship/mongodb-atlas/bestock-database/Product", "foreignKey": "category", "isList": true } }
同时确保Category的属性schema中products字段类型正确(数组存储ObjectId),当前配置符合要求:
{ "title": "Category", "bsonType": "object", "required": [ "_id", "_partition", "name", "image" ], "properties": { "_id": { "bsonType": "objectId" }, "_partition": { "bsonType": "string" }, "name": { "bsonType": "string" }, "image": { "bsonType": "string" }, "products": { "bsonType": "array", "items": { "bsonType": "objectId" } }, "company_id": { "bsonType": "objectId" } } }
3. 插入数据时维护双向关联
插入Product时,需同时将Product实例添加到对应Category的products列表中,确保双向关联数据同步:
realm.write { // 假设已获取或创建目标Category val targetCategory = this.query<Category>("_id == $0", categoryId).first().find() ?: return@write // 创建并插入Product val newProduct = copyToRealm(Product().apply { name = "示例产品" quantity = 10 price = 29.9f // 其他字段赋值 }) // 将Product添加到Category的products列表 targetCategory.products.add(newProduct) }
额外检查:Partition Key一致性
确保Category和Product的_partition字段值完全相同,Realm Sync基于Partition Key隔离数据,不同Partition下的对象无法建立跨分区关联。
内容的提问来源于stack exchange,提问作者Besart
相关产品推荐
相关产品推荐

