Note that there are some explanatory texts on larger screens.

plurals
  1. POGORM get/find resource by ID using MongoDB in Grails
    primarykey
    data
    text
    <p>Grails makes it easy to <a href="https://grails.github.io/grails-doc/latest/ref/Domain%20Classes/get.html" rel="nofollow">get</a> a domain object by ID (handy for building a REST API).</p> <p>A controller to retrieve a resource can be as simple as:</p> <p><strong>MetricController.groovy</strong></p> <pre><code>import grails.converters.JSON class MetricController { def index() { def resource = Metric.get(params.id) render resource as JSON } } </code></pre> <p><br> When using the Grails plugin for MongoDB GORM (<code>compile ":mongodb:1.2.0"</code>), the default <code>id</code> type of <code>Long</code> <a href="http://blog.mongodb.org/post/18510469058/grails-in-the-land-of-mongodb" rel="nofollow">needs to be changed</a> to type <code>String</code> or <code>ObjectId</code>.</p> <p><strong>Metric.groovy</strong></p> <pre><code>import org.bson.types.ObjectId class Metric { static mapWith = "mongo" ObjectId id String title } </code></pre> <p><br> However, doing a <code>.get(1)</code> will now result in:</p> <pre><code>Error 500: Internal Server Error URI /bow/rest/metric/1 Class java.lang.IllegalArgumentException Message invalid ObjectId [1] </code></pre> <p><br> I took a guess and changed the controller to use <code>findById</code>:</p> <pre><code>def resource = Metric.findById(new ObjectId(new Date(), params.id.toInteger())) </code></pre> <p>That fixed the error, but it fails to find the object (always returns null).</p> <p>For example, using the id of "-1387348672" does not find this test object:</p> <pre><code>{ "class" : "Metric", "id" : { "class" : "org.bson.types.ObjectId", "inc" : -1387348672, "machine" : 805582250, "new" : false, "time" : 1371329632000, "timeSecond" : 1371329632 }, "title" : "Test" } </code></pre> <p><br> The <code>ObjectId.inc</code> field may not even be the correct field to use for the resource ID.</p> <p>So, what is the simplest way to retrieve a domain object by ID when using MongoDB?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload