React Native集成MongoDB App Services时自定义嵌入对象报错
问题描述
我正在开发一个以MongoDB App Services为后端的React Native应用,此前功能运行一切正常,但添加自定义嵌入对象类型User_location后,SDK无法识别该类型。
模型代码
import "react-native-get-random-values"; import Realm, { BSON, ObjectSchema } from "realm"; // import { User_location } from "./User_location"; export class User extends Realm.Object<User> { _id!: BSON.ObjectId; userName?: string; firstName?: string; lastName?: string; email!: string; avatar?: string; userId!: string; admin!: boolean; location?: User_location; static schema: ObjectSchema = { name: "User", primaryKey: "_id", properties: { _id: { type: "objectId", default: () => new BSON.ObjectId() }, userName: "string?", firstName: "string?", lastName: "string?", email: "string", avatar: "string?", userId: "string", admin: "bool", location: "User_location?", }, }; } export class User_location extends Realm.Object { latitude!: number; longitude!: number; static schema: ObjectSchema = { name: "User_location", embedded: true, properties: { latitude: "double", longitude: "double", }, }; }
报错信息
[Error: Object type 'User_Location' not found in schema.]
我严格遵循MongoDB官方文档中的示例实现,但仍出现该问题,请问我遗漏了什么?
解决方案
1. 修正大小写不匹配问题
报错提示找不到User_Location,但你的本地模型定义是User_location(小写l)。Realm对象类型名称大小写敏感,请检查:
- 代码中所有引用该嵌入对象的位置,确保名称和模型完全一致
- App Services后台的集合Schema定义,确认
location字段对应的嵌入对象名称为User_location
2. 确保嵌入对象Schema被正确注册
- 如果两个类在同一文件中,初始化Realm时必须将
User_location加入schema数组:const realm = await Realm.open({ schema: [User, User_location], // 同时包含User和User_location的Schema // 其他配置项(如sync等) }); - 如果
User_location是单独文件,取消注释导入语句import { User_location } from "./User_location";,并确保路径正确。
3. 同步后台与本地Schema
若开启了Realm Sync,需保证App Services后台的User集合Schema中,location字段的嵌入对象定义和本地模型完全一致,包括字段类型、名称大小写。
4. 清除本地缓存数据
旧的本地Realm缓存可能导致Schema冲突,可尝试:
- 卸载并重新安装应用
- 调用
Realm.deleteFile()删除本地数据库后重新初始化Realm
内容的提问来源于stack exchange,提问作者Sven Hager
相关产品推荐
相关产品推荐

