Grails Mongodb Embedded Documents ?Bug?

1.1k Views Asked by At

I have this simple model:

abstract class Info {
    ObjectId id
    Date dateCreated
    Date lastUpdated
}
class Question extends Info {
    String title
    String content
    List<Answer> answers = []
    static embedded = ['answers']
}
class Answer {
    String content
}

Written this way, answer are embedded in question (and no id is maintained for answer). I want to maintain the id, dateCreated, and lastUpdated fields for every answer. So I try the following:

class Answer extends Info {
    String content
}

When I run a simple test case (save a question with 1 answer), I get the following:

> db.question.find()
{ "_id" : ObjectId("4ed81d47e4b0777d795ce3c4"), "answers" : [ { "content" : "its very 
cool", "dateCreated" : null, "lastUpdated" : null,  "version" : null } ], "content" : 
"whats up with mongodb?", "dateCreated" : ISODate("2011-12-02T00:35:19.303Z"), 
"lastUpdated" : ISODate("2011-12-02T00:35:19.303Z"), "title" : "first question", 
"version" : 0 }

I notice here that fields dateCreated and lastUpdate are not auto-maintained by Grails. Also version field was added but has a null value as well, but interestingly no _id field created (even if I defined id in Info class).

In a second scenario, I try this:

class Answer {
    ObjectId id
    String content
}

and I get the following output:

> db.question.find()
{ "_id" : ObjectId("4ed81c30e4b076cb80ec947d"), "answers" : [ { "content" : "its very 
cool" } ], "content" : "whats up with mongodb?", "dateCreated" : ISODate("2011-12-
02T00:30:40.233Z"), "lastUpdated" : ISODate("2011-12-02T00:30:40.233Z"), "title" : 
"first question", "version" : 0 }

This time, id is also not created for the embedded document. Any explanation for this scenarios ? Why there is no id property, and why dateCreated, lastUpdated, and version are null? Is this intended to work this way, or is it a bug?

Thank you,

1

There are 1 best solutions below

1
On

this is probably due to how the grails framework does the conversion (the GORM module). You may have quicker / better answers from the grails forum. Basically it seems that some of the automatic behavior (fill in dates and objectid) is only done for the root object, not subobjects. You can also checkout an alternative ORM based on morphia: http://www.grails.org/plugin/mongodb-morphia