Search code examples
grailsgrails-ormgrails-3.0gorm-mongodb

Is there a way to control loading relations in gorm with mongodb?


I'm building a REST api with grails 3 and mongo. I have encountered a problem when i need to marshal an object graph with a bigger depth.

I have the following domains:

class Category extends Resource {
    /* other fields */

    Category parent
}

class Product extends Resource {
    /* other fields */

    List<Category> categories
    static hasMany = [categories: Category]
}

I have in the database the following structure(simplified for the sake of understanding):

categories:
{name: 'cat1'}
{name: 'cat2', parent: 'cat3'}
{name: 'cat3', parent: 'cat4'}
{name: 'cat4', parent: 'cat5'}
{name: 'cat5'}

product: 
{categories: ['cat1', 'cat2']}

I am extending from RestfullController when creating my controllers. I want to be able to get a product and have the categories with parents in the returned json.

I get the following results:

/product/${id} 
{
    id: '...',
    categories: [{
        id: '...',
        name: 'cat1'
    }, {
        id: '...',
        name: 'cat2',
        parent: { id: '...' }
    }]
} 

/category/cat2id 
{
    id: '...',
    name: 'cat2',
    parent: { id: '...' }
}

/category
[{
    id: '...',
    name: 'cat1'
},{
    id: '...',
    name: 'cat5'
},{
    id: '...',
    name: 'cat4',
    parent: {
        id: '...',
        name: 'cat5'
    }
},{
    id: '...',
    name: 'cat3',
    parent: {
        id: '...',
        name: 'cat4',
        parent: {
            id: '...',
            name: 'cat5'
        }
    }
},{
    id: '...',
    name: 'cat2',
    parent: {
        id: '...',
        name: 'cat3',
        parent: {
            id: '...',
            name: 'cat4',
            parent: {
                id: '...',
                name: 'cat5'
            }
        }
    }
}]

Why would Category.list() load the whole category object graph, and Category.get(), Product.get() and Product.list() would not load it? Is there a way to control this behaviour ?


Solution

  • The way Grails works is that it will only render associations that have already been loaded from the database, hence why you get some associations rendered and others not.

    There is no built in way to control this behaviour other than writing your own marshaller. See http://grails.github.io/grails-doc/latest/guide/webServices.html#renderers