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

Saving a record that violates a unique index constraint appears to persist data, but doesn't

    • Type: Icon: Task Task
    • Resolution: Done
    • 12_01_17
    • Affects Version/s: None
    • Component/s: None
    • Labels:

      Given the following model (with a unique index defined):

      class Animal
      include Mongoid::Document
      field :name

      index :name, :unique => true
      create_indexes
      end

      Creating an initial record succeeds, and the record can be refound given its id:

      first = Animal.create!
      Animal.find(first.id)

      Creating a second record appears to succeed. However, calling find with the record's id raises a Mongoid::Errors::DocumentNotFound exception; it was never persisted to mongodb.

      second = Animal.create!
      Animal.find(second.id)

      Going into mongodb itself and inserting the document makes it clear that the second create! should fail - the unique constraint has been violated as both names are null ({{E11000 duplicate key error index: development.animals.$name_1 dup key: { : null }}}).

            Assignee:
            Unassigned Unassigned
            Reporter:
            tomafro Tom Ward
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: