-
Type: Bug
-
Resolution: Duplicate
-
Priority: Major - P3
-
None
-
Affects Version/s: None
-
Component/s: Kotlin
-
None
-
Java Drivers
Summary
When inserting an object into the collection, the type is not being appended. However, during serialization with the codec, the output appears correct.
version 5.0.0
How to Reproduce
Codecs:
CodecRegistries.fromRegistries( CodecRegistries.fromCodecs( KotlinSerializerCodec.create<Polymorphic>( serializersModule = defaultSerializersModule + SerializersModule { polymorphic(Polymorphic::class) { subclass(Polymorphic1::class) subclass(Polymorphic2::class) } }, bsonConfiguration = BsonConfiguration(classDiscriminator = "_t", encodeDefaults = true) ) ), CodecRegistries.fromProviders( KotlinCodecProvider() ), Bson.DEFAULT_CODEC_REGISTRY, )
Data classes:
@Serializable abstract class Polymorphic { abstract val id: ObjectId } @Serializable @SerialName(value = "ONE") data class Polymorphic1( @SerialName(value = "_id") @Serializable(with = ObjectIdSerializer::class) override val id: ObjectId, val a: String, val b: String, val c: Boolean, ) : Polymorphic() @Serializable @SerialName(value = "TWO") data class Polymorphic2( @SerialName(value = "_id") @Serializable(with = ObjectIdSerializer::class) override val id: ObjectId, val d: Boolean, val e: Int, val f: String, ) : Polymorphic()
Sample code:
__
val polymorphicCollection = database.getCollection<Polymorphic>("polymorphic") val registry = polymorphicCollection.codecRegistry[Polymorphic::class.java] var document = BsonDocument() var writer = BsonDocumentWriter(document) val polymorphic1 = Polymorphic1(ObjectId(),"a","b",true) registry.encode(writer,polymorphic1,EncoderContext.builder().build()) writer.flush() println(document.toJson(JsonWriterSettings.builder() .indent(true) .build() )) document = BsonDocument() writer = BsonDocumentWriter(document) val polymorphic2 = Polymorphic2(ObjectId(),true,1,"f") registry.encode(writer,polymorphic2,EncoderContext.builder().build()) writer.flush() println(document.toJson(JsonWriterSettings.builder() .indent(true) .build() )) runBlocking { polymorphicCollection.drop() polymorphicCollection.insertOne(polymorphic1) polymorphicCollection.insertOne(polymorphic2) }
Additional Background
Code output:
{ "_t": "ONE", "_id": { "$oid": "6608b5ef80e74b7949643522" }, "a": "a", "b": "b", "c": true } { "_t": "TWO", "_id": { "$oid": "6608b5ef80e74b7949643523" }, "d": true, "e": 1, "f": "f" }
Database output:
testing> db.polymorphic.find().pretty() [ { _id: ObjectId('6608b5ef80e74b7949643522'), a: 'a', b: 'b', c: true }, { _id: ObjectId('6608b5ef80e74b7949643523'), d: true, e: 1, f: 'f' } ]
- duplicates
-
JAVA-5304 bson-kotlinx & polymorphic MongoCollection instances
- Closed