How to store lists of embedded documents with MongoDB under Grails?
I'm having problem storing lists of embedded documents/objects in MongoDB
using the Grails MongoDB plugin. I used the information given in the
documentation in chapter 3 but only got the embedding of one object
working.
For testing purposes I created two domain objects Person and Address in a
new Grails project. They look like this:
class Person {
ObjectId id
String firstName
String lastName
Address address
List otherAddresses = []
static embedded = ['address', 'otherAddresses']
}
class Address {
String street
String postCode
String city
}
When I execute the following lines in Bootstrap.groovy it stores two
Person objects in MongoDB - both have a correct address but in person1 the
otherAddresses List is "[ null ]" and in person2 the otherAddresses List
is "[ { "street" : "Second 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()
Resulting Database Entries:
{ "_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}
Further Notes:
I'm using a pure mongodb approach (no a hybrid together with Hibernate)
I'm working on a Windows 8 machine using Grails 2.2.1 running mongo db 2.4.4
Person is a domain object in /grails-app/domain and Address is a "normal"
groovy class in /src/groovy (I can put it in domain folder but that has no
effect)
Everything is set to be nullable in Config.groovy:
grails.gorm.default.constraints = { '*'(nullable: true) }
BuildConfig.groovy has the plugin entry: compile ":mongodb:1.3.0"
What am I doing wrong? How can I store a list of embedded objects using
the Grails mechanism?
No comments:
Post a Comment