-
Type: Bug
-
Resolution: Fixed
-
Priority: Major - P3
-
Affects Version/s: 6.0.3, 7.0.2, 6.4.2
-
Component/s: Attributes
-
Environment:OSX, Ruby 2.5, Rails 5.0.7 though i imagine its an issue on any platform.
Simple repeatable test:
class Test include Mongoid::Document field :test field :stuff end doc = Test.create! :test => "something", :stuff => "here"
Without compact option, returns as expected:
2.5.0 :038 > doc.as_json => {"_id"=>BSON::ObjectId('5ccc7c2cb0602182d7c7a258'), "stuff"=>"here", "test"=>"something"}
With compact option set to true, returns nil
2.5.0 :039 > doc.as_json(:compact => true)
=> nil
Root cause the Document.as_json method uses the reject! method which per the ruby docs "returns nil if no changes were made."
Mongoid as_json method:
def as_json(options = nil) if options && (options[:compact] == true) super(options).reject! { |k,v| v.nil? } else super(options) end end
Ruby reject! method:
https://ruby-doc.org/core-2.5.0/Array.html#method-i-reject
Possibly just use reject instead.
- links to