title: Spring Data MongoDB - Audit issue with unique index
body: <p>If the createdBy references to a document with unique indexes, it fails throwing <em>dup key</em> error.</p>
  
  <p><strong>AbstractDocument.java</strong></p>
  
  <pre><code>public abstract class AbstractDocument implements Auditable&lt;User, String&gt; {
  
    @Version
    private Long version;
  
    @Id
    private String id;
  
    private User createdBy;
  
    private DateTime createdDate;
  
    private User lastModifiedBy;
  
    private DateTime lastModifiedDate;
  
  }
  </code></pre>
  
  <p><strong>User.java</strong></p>
  
  <pre><code>@Document(collection = "users")
  public class User extends AbstractDocument {
  
      private String name;
      private String surname;
  
      @Indexed(unique = true)
      private String username;
  }
  </code></pre>
  
  <p><strong>Book.java</strong></p>
  
  <pre><code>@Document(collection = "books")
  public Book extends AbstractDocument {
  
       private String title;
  }
  </code></pre>
  
  <p>Now, I have a script (Spring Batch) which initializes the db with some books. The script defines the auditor this way:</p>
  
  <pre><code>@Configuration
  @EnableMongoAuditing
  public class MongoConfig {
  
     @Bean
     public AuditorAware&lt;User&gt; auditorProvider() {
        return new AuditorAware&lt;User&gt;() {
  
          @Override
          public User getCurrentAuditor() {
              User auditor = new User();
              auditor.setUsername("init-batch");
              auditor.setName("Data initializer");
              auditor.setSurname("Data initializer");
  
              return auditor;
          }
      };
    }
  }
  </code></pre>
  
  <p>The script in somewhere does (for each book I need to persist) <strong>bookRepository.save(book)</strong></p>
  
  <p>The first book is persisted, but the second one throws:  </p>
  
  <p><em>nested exception is com.mongodb.DuplicateKeyException: Write failed with error code 11000 and error message 'E11000 duplicate key error index: mydb.books.$createdBy.username dup key: { : "init-batch" }'</em> </p>
  
  <p>Why? The unique index is for <em>users</em> collection, why is it checked for audit references?</p>