gpt4 book ai didi

mongodb - 具有关联的Grails MongoDB更新对象

转载 作者:行者123 更新时间:2023-12-02 16:00:30 25 4
gpt4 key购买 nike

当我尝试更新具有与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处理。任何建议或想法都将不胜感激。

最佳答案

您不应该将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
}

因此,您可以按照其原始的up来使用mongo。查询也更加简单快捷。

关于mongodb - 具有关联的Grails MongoDB更新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31565242/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com