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

bson-kotlinx & polymorphic MongoCollection instances

    • Type: Icon: Bug Bug
    • Resolution: Fixed
    • Priority: Icon: Major - P3 Major - P3
    • 4.11.2, 5.1.0
    • Affects Version/s: None
    • Component/s: Kotlin
    • Labels:
      None
    • Java Drivers
    • Not Needed
    • Hide

      1. What would you like to communicate to the user about this feature?
      2. Would you like the user to see examples of the syntax and/or executable code and its output?
      3. Which versions of the driver/connector does this apply to?

      Show
      1. What would you like to communicate to the user about this feature? 2. Would you like the user to see examples of the syntax and/or executable code and its output? 3. Which versions of the driver/connector does this apply to?

      The following code shows a bug deserializing data into a MongoCollection

      
      @Serializable
      sealed interface Pet {
          val name: String
      }
      
      @Serializable
      data class Dog(
          @Contextual
          @SerialName("_id")
          val id: ObjectId,
          override val name: String,
          val favoriteToy: String,
      ) : Pet
      
      @Serializable
      data class Cat(
          @Contextual
          @SerialName("_id")
          val id: ObjectId,
          override val name: String,
          val favoritePlace: String,
      ) : Pet
      
      suspend fun main() {
          val winston = Dog(ObjectId(), "Winston", "Ball")
      
          val collection = MongoClient.create().getDatabase("test").getCollection<Pet>("Pet")
          collection.insertOne(winston)
      
          collection.withDocumentClass<Document>().find().first().also { println(it) }
          collection.withDocumentClass<Dog>().find().first().also { println(it) }
          collection.withDocumentClass<Pet>().find().first().also { println(it) }  // FAILS with a codec error:
      
      
      Stack trace:
      Exception in thread "main" org.bson.BsonInvalidOperationException: Reading field '_id' failed expected STRING type but found: OBJECT_ID.
      	at org.bson.codecs.kotlinx.DefaultBsonDecoder.decodeString(BsonDecoder.kt:302)
      	at kotlinx.serialization.encoding.AbstractDecoder.decodeStringElement(AbstractDecoder.kt:58)
      	at kotlinx.serialization.internal.AbstractPolymorphicSerializer.deserialize(AbstractPolymorphicSerializer.kt:52)
      	at org.bson.codecs.kotlinx.KotlinSerializerCodec.decode(KotlinSerializerCodec.kt:182)
      
      }
      
      

            Assignee:
            ross@mongodb.com Ross Lawley
            Reporter:
            ross@mongodb.com Ross Lawley
            Votes:
            2 Vote for this issue
            Watchers:
            6 Start watching this issue

              Created:
              Updated:
              Resolved: