当我尝试更新与Profile对象具有hasOne关联的用户域模型时,我似乎无法理解我当前在哪里出错。
我的域名模型如下:
class User {
static hasOne = [profile: Profile]
static fetchMode = [profile: 'eager']
ObjectId id
String username
}
class Profile {
static belongsTo = [user: User]
ObjectId id
String familyName
String givenName
}
我能够最初使用个人资料来保留用户,但在尝试更新用户对象时,我会收到验证错误。
Validation error occurred during call to save():
- Field error in object 'co.suitable.User' on field 'profile.familyName': rejected value [null]
- Field error in object 'co.suitable.User' on field 'profile.givenName': rejected value [null]
我可以在保存对象之前打印出user.profile ID以及user.profile.familyName。如下所示:
println(user.profile.familyName)
println(user.profile.id.toString())
user.save(flush: true, failOnError: true)
但是我在保存之前仍然会收到验证错误,我想象println(user.profile.familyName)
调用正在获取配置文件对象(如果它尚未加载),我认为设置fetchMode会有处理。
当我这样做时,该对象能够成功保存并保存:
user.profile = Profile.findById(user.profile.id)
println(user.profile.id.toString())
user.save(flush: true, failOnError: true)
我可以在服务中包装它,但我希望有一个解决方案,如果可能的话将由Grails处理。任何建议或想法都非常感谢。
答案 0 :(得分:0)
您不应该将SQL DB的逻辑应用于Mongo 1到1. Mongo和其他面向文档的DB最初并不打算存储集合之间的连接。有一些解决方法,例如db-refs
,但是要谨慎使用它们。
对于你的情况 - hasOne
- 我建议使用mongo的subdocuments
(镜像为GORM的embedded
个对象)而不是引用:
class User {
ObjectId id
String username
Profile profile
static embedded = [ 'profile' ]
}
class Profile {
String familyName
String givenName
}
因此你根据它的原始puprose使用mongo。查询也更简单,更快。