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

Duplicate embedded document created on save (repro included)

    • Type: Icon: Bug Bug
    • Resolution: Done
    • Priority: Icon: Major - P3 Major - P3
    • 7.0.0
    • Affects Version/s: None
    • Component/s: None
    • Labels:
      None

      The following example reproduces the issue where duplicate embedded documents ends up created after a call to save. Run the code below then check the "instruments" embedded collection in the "members" embedded collection of "bands". There are two documents with the same id.

      A couple of interesting observations:

      1. The duplication does not occur when saving the root (b) or the leaf (trumpet) document.
      2. The duplication does not occur when removing the "validates_presence_of" validation in the "Member" document definition.

      #!/usr/bin/env ruby
      require 'mongoid'
      
      DB_NAME = 'test_find_or_initialize_by'
      
      class Band
        include Mongoid::Document
        field :active, type: Boolean
        embeds_many :members, inverse_of: :band
        validates_presence_of :members, if: lambda { |b| b.active }
      end
      
      class Member
        include Mongoid::Document
        field :name, type: String
        embeds_many :instruments, inverse_of: :member
        embedded_in :band, inverse_of: :members
      
        validates_presence_of :band # Comment this out and the bug goes away!
      end
      
      class Instrument
        include Mongoid::Document
        field :name, type: String
        embedded_in :member, inverse_of: :instruments
      end
      
      Mongoid.load_configuration(sessions: { default: { database: DB_NAME, hosts: ['localhost'], options: {} } })
      
      b = Band.create!(active: false)
      alice = b.members.create(name: 'alice')
      b.active = true
      trumpet = alice.instruments.build(name: 'trumpet')
      alice.save!
      # You now have two "trumpet" documents in the "alice" document
      

            Assignee:
            emily.stolfo Emily Stolfo
            Reporter:
            raphael Raphaƫl Simon
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: