-
Type:
Improvement
-
Resolution: Fixed
-
Priority:
Unknown
-
Affects Version/s: None
-
Component/s: BSON
-
None
-
Major Change
-
-
- The Change
-
Currently, `BSON::ObjectId#as_json` will return `{ "$oid" => "03d623ca58edf9046e207565" }`
This PR does what 99% of users prefer: return a plain String `"03d623ca58edf9046e207565"`
I've included a "Breaking change" notice in the docs for this.
-
-
- Why
-
While `$oid` may be the correct way to represent an ObjectID in strict "BSON", it is not a practical way to represent an ObjectID in "JSON" as used in real world apps. The standard use case for JSON (`.as_json` method) is *to serialize objects for HTTP APIs*. The primary goal of Mongoid is for us as developers not to have to worry about BSON internal representations; instead we think in terms of the Ruby app domain. (Mongoid / Mongo Ruby Driver handles the BSON nuts-and-bolts for us.)
-
-
- Other Ideas
-
We could also add `BSON::ObjectId#as_bson` and `Object#as_bson` (which delegates to `.as_json` in all cases except `ObjectId`.) I don't think it's particularly useful, but I'd be happy to implement it if the Mongo team would like. (We'd probably want to call `mongoize` or `evolve` as well...)
-
-
- More Background
-
The current behavior drives Rails users absolutely crazy as you can see in the following issues, and *nearly everyone ends up monkey-patching this method* after hours of debugging frustration. Here are some a few examples out of hundreds:
- https://medium.com/aviabird/mongoid-how-to-serialize-to-json-with-a-string-id-attribute-2d5c1bc284a7
- https://stackoverflow.com/questions/23505247/have-to-json-return-a-mongoid-as-a-string
- https://stackoverflow.com/questions/18646223/ruby-model-output-id-as-object-oid
- https://github.com/nesquena/rabl/issues/337
Incidentally, Mongoid 3.1 and earlier used to serialize this as a String; when it changed to `$oid` it broke my and many other users apps--this unexpected behavior causes lots of bugs.
- is related to
-
MONGOID-5162 Remove BSON::ObjectId#as_json override
-
- Closed
-
-
MONGOID-5234 Add Feature Flag: Remove BSON::ObjectId#as_json override
-
- Closed
-
-
RUBY-2810 Make as_json serializations user-friendly for numeric types
-
- Closed
-
- links to