Skip to content

MONGOID-5158 - BSON::ObjectId#as_json and #to_json should serialize as a String without "$oid" #5054

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions docs/release-notes/mongoid-7.4.txt
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,40 @@ please consult GitHub releases for detailed release notes and JIRA for
the complete list of issues fixed in each release, including bug fixes.


BSON::ObjectId ``#as_json`` returns String
------------------------------------------

**Breaking change:** BSON::ObjectId ``#as_json`` used for JSON serialization
now returns a String value. Note this will also affect the behavior of the ``#to_json`` method.

.. code-block:: ruby

id = BSON::ObjectId("03d623ca58edf9046e207565")

id.as_json #=> "03d623ca58edf9046e207565"

id.to_json #=> "\"03d623ca58edf9046e207565\""

In Mongoid 7.3 and prior, this method returned a Hash with ``"$oid"`` as its key:

.. code-block:: ruby

id.as_json #=> { "$oid" => "03d623ca58edf9046e207565" }

id.to_json #=> "{\"$oid\":\"03d623ca58edf9046e207565\"}"

If you wish to preserve the legacy behavior, you may add the following
patch when initializing your application:

.. code-block:: ruby

class BSON::ObjectId
def as_json(options = nil)
{ "$oid" => to_s }
end
end


``===`` Operator Matches Ruby Semantics
---------------------------------------

Expand Down
2 changes: 1 addition & 1 deletion lib/mongoid/extensions.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

class BSON::ObjectId
def as_json(options = nil)
{ "$oid" => to_s }
to_s
end
end

Expand Down
4 changes: 2 additions & 2 deletions spec/mongoid/extensions_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@
described_class.new
end

it "returns the $oid plus string" do
expect(object_id.as_json).to eq("$oid" => object_id.to_s)
it "returns as a string" do
expect(object_id.as_json).to eq(object_id.to_s)
end
end
end
Expand Down