2013-08-18 40 views
1

我在使用Grails MongoDB插件在MongoDB中存儲嵌入式文檔/對象列表的問題。我使用了第3章documentation中給出的信息,但只有一個對象的嵌入工作。如何在Grails下使用MongoDB存儲嵌入式文檔列表?

出於測試目的,我在一個新的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列表是「[空]」,並在PERSON2其他地址列表是「[{」street「:」第二街道。 164" , 「城市」: 「紐約」, 「郵編」: 「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} 

其它注意事項:

  • 我正在使用純mongodb方法(沒有與Hibernate混合在一起)

  • 我正在使用Windows 8機器使用Grails 2.2.1運行mongo db 2.4.4

  • Person是/ grails-app/domain中的域對象,Address是/ src/groovy中的「普通」groovy類(我可以將它放在域文件夾中但沒有任何影響)

  • 一切被設定爲可空Config.groovy中:grails.gorm.default.constraints = { '*'(可爲空:真)}

  • BuildConfig.groovy具有插件條目:編譯「:mongodb:1.3.0」

我在做什麼錯?如何使用Grails機制存儲嵌入對象的列表?

回答

0

我想你是第二個人而不是地址對象添加地圖。是否有任何理由爲每個人添加其他地址不同?

我認爲這應該工作,雖然我沒有測試它:

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()