Uploaded image for project: 'Mongoid'
  1. Mongoid
  2. MONGOID-4733

Document#as_json with :compact option returns nil if none of the fields are nil

    • Type: Icon: Bug Bug
    • Resolution: Fixed
    • Priority: Icon: Major - P3 Major - P3
    • 7.1.0.rc0, 7.0.3, 6.4.4
    • 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.

       

       

       

            Assignee:
            oleg.pudeyev@mongodb.com Oleg Pudeyev (Inactive)
            Reporter:
            cdiebner Chris
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated:
              Resolved: