title: How to convert a Object with enum attribute in Spring Data MongoDB?
body: <p>I have the following class that I want to save and query from MongoDB. I managed to set a custom convert that converts from InstanceType to String and String to InstanceType. InstanceType is a custom enum that will be stored in a different way!</p>
  
  <pre><code>@Document
  public class Instance {
  
    private String name;
    private InstanceType type;
    private List&lt;Configuration&gt; configurations;
    private Map&lt;String, String&gt; properties;
  
  }
  </code></pre>
  
  <p>MongoConfiguration class</p>
  
  <pre><code>@Bean
  @Override
  public CustomConversions customConversions() {
    List&lt;Converter&lt;?, ?&gt;&gt; converters = new ArrayList&lt;&gt;();
    converters.add(new InstanceTypeToStringConverter());
    converters.add(new StringToInstanceTypeConverter());
    return new CustomConversions(converters);
  }
  
  @Bean
  @Override
  public MappingMongoConverter mappingMongoConverter() throws Exception {
    MongoMappingContext mappingContext = new MongoMappingContext();
    DbRefResolver databaseResolver = new   DefaultDbRefResolver(mongoFactory());
    MappingMongoConverter mongoConverter = new MappingMongoConverter(databaseResolver, mappingContext);
    mongoConverter.setCustomConversions(customConversions());
    mongoConverter.afterPropertiesSet();
    return mongoConverter;
  }
  </code></pre>
  
  <p>The problem I'm having is that when I try to query the Instance object in MongoDB, Spring uses StringToInstanceType to convert "name" attribute. Why Spring is using this converter? This converter should not only be applied to "type" attribute?</p>
  
  <p>This is the query I'm trying to execute:</p>
  
  <pre><code>public Instance getInstance(InstanceType type, String name) {
    return mongoTemplate.findOne(Query.query(
      Criteria.where("type").is(type)
                .and("name").is(name)
      ), Instance.class, COLLECTION_INSTANCES);
  }
  </code></pre>
  
  <p>Type attribute is converted using InstanceTypeToStringConverter (Thats OK because the source is InstanceType and target is String)</p>
  
  <p>Name attribute is converted using StringToInstanceTypeConverter (It's wrong because the source is String and target is a String)</p>
  
  <p>Because os this behavior, the query is returning NULL.
  Let's say I have the follow object in MongoDB:</p>
  
  <pre><code>{"type": "user", "name": "Sandro"}
  </code></pre>
  
  <p>InstanceType.USER is converted to "user" (InstanceTypeToStringConverter).</p>
  
  <p>"Sandro" is converted to null (StringToInstanceTypeConverter) because InstanceType.getInstanceType("Sandro") returns null.</p>
  
  <p>In this case Spring will query mongo this way:</p>
  
  <pre><code>Where type = "user" and name = null
  </code></pre>