1

I was following Grails 2.4.4 documentation to make a Map of Objects, but my objects were not being persisted to Mongo DB. So, I decided to make a sanity check using the exactly same example provided by the documentation and it also did not work.

Steps:

grails create-app test

Next, I included the mongo plugin to my BuilConfig.groovy :

compile ":mongodb:3.0.3"
//runtime ":hibernate4:4.3.6.1"

Then, I configured my DataSource.groovy:

environments {
    production {
        grails {
            mongo {
                replicaSet = [ "xxxxxxxx"]
                username = "xxxx"
                password= "xxxxxxxxxxxxxx"
                databaseName = "xxxxxx"
            }
        }
    }
    development {
        grails {
            mongo {
                replicaSet = [ "xxxxxxxx"]
                username = "xxxx"
                password= "xxxxxxxxxxxxxx"
                databaseName = "xxxxxx"
            }
        }
    }
    test {
        grails {
            mongo {
                replicaSet = [ "xxxxxxxx"]
                username = "xxxx"
                password= "xxxxxxxxxxxxxx"
                databaseName = "xxxxxx"
            }
        }
    }
}

Here is my Book domain class:

package test

class Book {

    String name
    Map authors
    static hasMany = [authors:Author]

    static constraints = {
    }
}

And here is my Author domain class:

package test

class Author {

    String name
    static constraints = {
    }
}

using the grails console, I ran the following script :

import test.*

def a = new Author(name:"Stephen King")

def book = new Book(name:"test")
book.authors = ["stephen":a]
book.save(failOnError:true)

And then, I took a look at my Mongo DB and I could not find the map that was supposed to be persisted.

{
    "_id": 1,
    "name": "test",
    "version": 0
}

I really appreciate if you have any clues of what is going on or if you know any workaround to persist a Mapin Grails.

Thanks

Shashank Agrawal
  • 25,161
  • 11
  • 89
  • 121
Pargles
  • 97
  • 2
  • 6

1 Answers1

1

Here you go. Add the following to your Book domain class:

static embedded = ["authors"]

On the second thought, why are you using a Map instead of List for authors?

Since this is a MongoDB database, it will save all the fields of Author.

Shashank Agrawal
  • 25,161
  • 11
  • 89
  • 121
  • Thanks @Shashank. This is just the example provided by the documentation which I will be using in a similar way. The embedded component saves the whole object, but what I need is just the "reference" to an existing object. It would be something like the following: `book: { "authors": { "awarded":2131, "acknowledged":324324, "mentioned": 6575234, } }` – Pargles Jul 29 '16 at 16:57