0

I have these models

abstract class Message : Data
data class TextMessage(val m: String): Message
data class ImageMessage(val m: ByteArray): Message

and I want to get a collection by the abstract class Message

database.getCollection<Message>

But it will actually be a implement class (TextMessage, ImageMessage) instance depending on it's content

when(val value = collection.findOne()) {
    is TextMessage -> {}
    is ImageMessage -> {}
}

how to do this?

1 Answers1

0

The KMongo library has 3 options for object mapping, and your solution will depend on which one is being used.

By default, Jackson engine is used. You can use POJO Codec engine by adding a -native suffix to the artifactId, or Kotlinx Serialization by adding a -serialization suffix to the artifactId.

https://litote.org/kmongo/quick-start/#object-mapping-engine

Depending on the engine used, apply how that engine handles polymorphism:

Aarjav
  • 1,334
  • 11
  • 22
  • I have added the @BsonDiscriminator annotation, and have done other thing like registering codec, but it is still not working. the kmongo official website document is not so clear enough for me – user16799920 Sep 06 '21 at 08:51
  • @user16799920 can you share your kmongo dependency or project? I had tried out all 3 before answering. The `@BsonDiscriminator` will only work if you are using `-native` dependency. Registering a codec should not be necessary unless there's something in `Data` class that we're not seeing. – Aarjav Sep 07 '21 at 22:57
  • It turns out that I was not using the -native dependency. Genuinely sorry for my carelessness – user16799920 Sep 08 '21 at 18:01