Grails 3 & relational domain mapping with Mongo

50 Views Asked by At

Trying to figure out if there is a way that I can relate these two domain objects in a similar way that I would if I were connected to an Oracle db.

gradle.properties

grailsVersion=3.2.9
gradleWrapperVersion=2.9
gormVersion=6.1.3.RELEASE

build.gradle

compile "org.grails.plugins:mongodb:6.1.3"
compile "org.mongodb:mongodb-driver:3.4.2"

Domain objects:

class Store {
  Long id
  // other properties
  Long sellerId
}

class Seller {
  Long id
  // other properties
}

I thought to do something like this:

class Store {
  Long id
  // other properties
  Long sellerId
  Seller seller
  Seller getSeller {
    Seller.findById(this.sellerId)
  }
}

In the case above, only sellerId is persisted to Mongo since it is not marked as embedded. This works great if I reference it in grails code - giving me valid values for all of the properties in store.seller. However, if I return a store from a controller, store.seller does not come through fully. The response JSON for store looks like this (notice how seller ONLY has the id property):

{
  id: 1,
  // other properties
  seller: {
    id: 22
  }
}

I have also tried something like this but afterLoad never gets hit:

class Store {
  Long id
  // other properties
  Long sellerId
  Seller seller

  def afterLoad() {
    seller = Seller.findById(this.sellerId)
  }
}

Is there a better way to go about doing this?

0

There are 0 best solutions below