Grails 2.4.4 Map of Objects example not being persisted to Mongo DB

169 views Asked by At

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

1

There are 1 answers

1
Shashank Agrawal On

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.