Uploaded image for project: 'Java Driver'
  1. Java Driver
  2. JAVA-3925

DocumentCodec ignores registry when writing Iterable or Map instances

    • Type: Icon: Improvement Improvement
    • Resolution: Fixed
    • Priority: Icon: Major - P3 Major - P3
    • 4.4.0
    • Affects Version/s: None
    • Component/s: Codecs
    • None
    • Minor Change
    • Needed

      Using POJO serialization, updates seem to be problematic. Considering this POJO:

       
      	@BsonId
      	public String key;
      	@BsonProperty("value")
      	public ObjectNode value;  
      
      

      Note, the "value" is Jackson.

      To support this, it was registered a custom Codec for ObjectNode. Updates will not invoke the codec. For example:

       
      	Document setters = new Document("value", Mappers.getJacksonMapper().createObjectNode());
      	Document d = new Document("$set", setters);
      	// does not invoke codec, you get []
      	pojoCollection.updateOne(new Document("_id", "key1"), d);
      

      The ObjectNode is replaced with [] in the resulting BSON, which makes subsequent POJO reads fail.

      After some investigation, it was identified the root cause is [this line](https://github.com/mongodb/mongo-java-driver/blob/r3.12.5/bson/src/main/org/bson/codecs/DocumentCodec.java#L192) in the DocumentCodec. [This line](https://github.com/mongodb/mongo-java-driver/blob/r3.12.5/bson/src/main/org/bson/codecs/DocumentCodec.java#L192) special-cases encoding instances of Iterable with its own encoder. Normally this is not an issue. However in this case it is an issue because ObjectNode extends JsonNode which implements Iterable<JsonNode>. This prevents the process from falling through to [this line](https://github.com/mongodb/mongo-java-driver/blob/r3.12.5/bson/src/main/org/bson/codecs/DocumentCodec.java#L197).

      As a workaround, the ObjectNode can be wrapped in some other class that does not implement Iterable, and provide a codec for that class as well.

            Assignee:
            jeff.yemin@mongodb.com Jeffrey Yemin
            Reporter:
            conchi.bueno@mongodb.com Conchi Bueno
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: