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

Coexisting instances are able to bypass the uniqueness validator on embedded docs

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

      I discovered this behavior using Mongoid 4.0.0, but I forked master and wrote a failing spec: https://github.com/mattruzicka/mongoid/commit/d8d7f894bbbddeffdf49b5aa16bf91c07395971b

      In case the spec is unclear, the behavior is reproducible with the following code:

      class Word
        include Mongoid::Document
        field :name, type: String
        embeds_many :definitions
      end
      
      class Definition
        include Mongoid::Document
        field :description, type: String
        embedded_in :word
        validates_uniqueness_of :description
      end
      
      word = Word.create(name: "Schadenfreude")
      same_word = Word.find(word._id)
      instance_1 = word.definitions.build(description: "Malicious joy")
      instance_2 = same_word.definitions.build(description: "Malicious joy")
      instance_1.save
      instance_2.save
      
      Word.find(word._id).definitions
      => [#<Definition _id: 545804884d61740e76040000, description: "Malicious joy">, #<Definition _id: 545804884d61740e76050000, description: "Malicious joy">]
      same_word.definitions
      

      On my production app, I think this behavior is resulting in parent documents that have embedded documents with duplicate fields for which there is a uniqueness validator.

      My ruby is 2.1.2p95

            Assignee:
            emily.stolfo Emily Stolfo
            Reporter:
            mattruzicka mattruzicka
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated:
              Resolved: