0

I have a Grails project the interacts with mongo DB. I would like to know what is the best practice for creating domain classes that represent nesting data.

data for example:

settings:{
  user:{id:1234 , name:"john"}
  colors:{header:"red" , footer:"white"}
}

would appreciate any help or code examples

Community
  • 1
  • 1
Shlomi Schwartz
  • 8,693
  • 29
  • 109
  • 186

2 Answers2

0

I think it is reasonable to presume that you are using mongodb plugin.

To put it simple:

Class Settings {
    int user_id
    String user_name
    String colors_header
    String colors_footer
}

If there is a legacy mongodb collection like you presented:

Class User {
    int id
    String name
}
Class Color {
    String header
    String footer
}
Class Settings{
  User user
  Colors colors
  static embedded = ['user','colors']
}
coderLMN
  • 3,076
  • 1
  • 21
  • 26
  • Thanks for the reply, I'm using the plugin. I'm a bit confused, If I use your first example, how is the nesting hierarchy preserved upon get query? could you give a code example? – Shlomi Schwartz Jan 02 '13 at 07:57
  • The first definition is not nested, but a simplified , flatened structure. If you want nested data, just take the second one, which matches you legacy data structure. – coderLMN Jan 02 '13 at 08:54
0

Since MongoDB is completely schemaless it means you are not limited to a fixed number of columns like in a relational database. so it fairly easy to create nesting data.

here is an example:

//the domain class
class Settings {
    Map user
    Map colors
}

//in the groovy controller
def s = new Settings(user: [name:"jhon"],colors:[header:"red" ,footer:"white"] )
s.save(flush: true)
Shlomi Schwartz
  • 8,693
  • 29
  • 109
  • 186