Grails makes it easy to get a domain object by ID (it is convenient for creating a REST API).
A controller for retrieving a resource can be as simple as:
MetricController.groovy
import grails.converters.JSON class MetricController { def index() { def resource = Metric.get(params.id) render resource as JSON } }
When using the Grails plugin for MongoDB GORM ( compile ":mongodb:1.2.0" ), you need to change the id type to enter String or ObjectId .
Metric.groovy
import org.bson.types.ObjectId class Metric { static mapWith = "mongo" ObjectId id String title }
However, executing .get(1) will result in:
Error 500: Internal Server Error URI /bow/rest/metric/1 Class java.lang.IllegalArgumentException Message invalid ObjectId [1]
I made an assumption and changed the controller to use findById :
def resource = Metric.findById(new ObjectId(new Date(), params.id.toInteger()))
This fixed the error, but could not find the object (always returns null).
For example, using the identifier "-1387348672" does not find this test object:
{ "class" : "Metric", "id" : { "class" : "org.bson.types.ObjectId", "inc" : -1387348672, "machine" : 805582250, "new" : false, "time" : 1371329632000, "timeSecond" : 1371329632 }, "title" : "Test" }
The ObjectId.inc field may not even be the right field to use the resource identifier.
So, what is the easiest way to get a domain object by ID when using MongoDB?