Mongoid: Serialize to JSON with an string id attribute

A quick hint, on how to have an 'id' attribute in Mongoid document JSON:

When you serialize Mongoid objects to JSON, you won't get ID attribute, similar to ActiveRecord. Instead you'll have "_id" attribute containing "$oid" value:

{
  "_id": {"$oid":"52d3fdfd53656e5180020000"},
  "changed_at":"2014-02-15",
  "created_at":"2014-01-13T15:53:49.444+01:00",
  "updated_at":"2014-01-13T15:53:49.444+01:00"
}

If you would prefer something like this:

{
  "id": "52d3fdfd53656e5180020000",
  "_id": {"$oid":"52d3fdfd53656e5180020000"},
  "changed_at":"2014-02-15",
  "created_at":"2014-01-13T15:53:49.444+01:00",
  "updated_at":"2014-01-13T15:53:49.444+01:00"
}

Just put this into your initializers (for example in config/initializers/mongoid.rb):

module Mongoid
  module Document
    def as_json(options={})
      attrs = super(options)
      attrs["id"] = attrs["_id"].to_s
      attrs
    end
  end
end

Categories: Ruby, Software

6 Comments

  1. Been there, done that. Maybe 3 weeks ago. I was really suprissed when I saw errors in “$oid”.

  2. How could you get errors in $oid? ;) If you don’t mess up with them, they should work.

  3. I was unprecise, excuse me. I serialized object to JSON and push it to queue. The queue consumer get errors when it has message like { _id: { “$oid”: “…” } }

  4. Thanks for sharing this!

  5. Maciej Mensfeld

    October 27, 2016 — 12:15

    Anytime :)

  6. Lucas Castro Oliveira

    January 12, 2017 — 20:44

    What about nested attributes Ids ? is it possible ?

Leave a Reply

Your email address will not be published. Required fields are marked *

*

Copyright © 2024 Closer to Code

Theme by Anders NorenUp ↑