我在使用Grails MongoDB插件在MongoDB中存储嵌入式文档/对象列表时遇到问题。我使用了第3章documentation中给出的信息,但只嵌入了一个有效的对象。
为了进行测试,我在一个新的Grails项目中创建了两个域对象Person和Address。他们看起来像这样:
class Person {
ObjectId id
String firstName
String lastName
Address address
List otherAddresses = []
static embedded = ['address', 'otherAddresses']
}
class Address {
String street
String postCode
String city
}
当我在Bootstrap.groovy中执行以下行时,它在MongoDB中存储了两个Person对象-都具有正确的地址,但在person1中otherAddresses列表是“[null]”,在person2中otherAddresses列表是“[{“street”:“第二街道。 164“,” city“:” New York“,” postCode“:” 13579“}]”
def address = new Address(street: "Mainstreet. 164", city: "New York", postCode:"12345")
def person1 = new Person(firstName: "John", lastName: "Doe")
person1.address = address
person1.otherAddresses.add(address)
println person1.otherAddresses // Result: "[mongoembeddedlisttest.Address : (unsaved)]"
person1.save()
person1.errors.allErrors.each { println it } // no errors
def person2 = new Person(firstName: "Jane", lastName: "Doe")
person2.otherAddresses += ['street': 'Second Street. 164', 'city': 'New York', 'postCode':'13579']
println person2.otherAddresses // Result: "[[street:Second Street. 164, city:New York, postCode:13579]]"
person2.save()
结果数据库条目:
{ "_id" : { "$oid" : "521089461a150b20390d61c2"} , "address" : { "city" : "New York" , "postCode" : "12345" , "street" : "Mainstreet. 164"} , "firstName" : "John" , "lastName" : "Doe" , "otherAddresses" : [ null ] , "version" : 0}
{ "_id" : { "$oid" : "521089461a150b20390d61c3"} , "firstName" : "Jane" , "lastName" : "Doe" , "otherAddresses" : [ { "street" : "Second Street. 164" , "city" : "New York" , "postCode" : "13579"}] , "version" : 0}
附加说明:
我究竟做错了什么?如何使用Grails机制存储嵌入式对象列表?
最佳答案
我认为您是在第二人称而不是Address对象中添加 map 。您为什么要为每个人添加不同的otherAddress吗?
我认为这应该有效,尽管我尚未测试过:
def address = new Address(street: "Mainstreet. 164", city: "New York", postCode:"12345")
def person1 = new Person(firstName: "John", lastName: "Doe")
person1.address = address
person1.otherAddresses.add(address)
println person1.otherAddresses // Result: "[mongoembeddedlisttest.Address : (unsaved)]"
person1.save()
person1.errors.allErrors.each { println it } // no errors
def person2 = new Person(firstName: "Jane", lastName: "Doe")
person2.otherAddresses += new Address('street': 'Second Street. 164', 'city': 'New York', 'postCode':'13579')
println person2.otherAddresses
person2.save()
关于list - 如何在Grails下使用MongoDB存储嵌入文档的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18297618/