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
February 16, 2014 — 21:29
Been there, done that. Maybe 3 weeks ago. I was really suprissed when I saw errors in “$oid”.
February 19, 2014 — 11:53
How could you get errors in $oid? ;) If you don’t mess up with them, they should work.
February 24, 2014 — 15:28
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”: “…” } }
October 21, 2016 — 11:52
Thanks for sharing this!
October 27, 2016 — 12:15
Anytime :)
January 12, 2017 — 20:44
What about nested attributes Ids ? is it possible ?