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

Using #only with embedded documents sets omitted fields to default values

    • 3

      If you have an object that has been retrieved via #only, you can be subject to data loss when saving that model.

      class Parent
        include Mongoid::Document
        embeds_one :child
      end
      
      class Child
        include Mongoid::Document
        embedded_in :parent
        field :a, :type => Integer, :default => 0
        field :b, :type => Integer, :default => 0
        field :c, :type => Integer, :default => 0
      end
      
      Parent.delete_all()
      p = Parent.new
      p.build_child(:a => 10, :b => 20, :c => 30)
      p.save()
      
      Mongoid::IdentityMap.clear
      p = Parent.only(:_id, 'child._id', 'child.a').first
      p.child.a = 40
      p.save()
      p.reload()
      p.child
      # => #<Child _id: 50eb642bdd365a121b00000c, a: 40, b: 0, c: 0>
      

            Assignee:
            oleg.pudeyev@mongodb.com Oleg Pudeyev (Inactive)
            Reporter:
            jonhyman Jon Hyman
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: