kmongo icon indicating copy to clipboard operation
kmongo copied to clipboard

[jackson mapping] Ids that wrap ObjectIds are not being properly deserialized for an inherited class

Open Welcius opened this issue 5 years ago • 3 comments

This issue is related to https://github.com/Litote/kmongo/issues/249, and still active in KMongo 4.2.4

@JsonTypeInfo(
    use = JsonTypeInfo.Id.NAME,
    include = JsonTypeInfo.As.EXISTING_PROPERTY,
    visible = true,
    property = "_type",
)
sealed class Animal {
    abstract val _id: Id<Animal>
    abstract val _type: String
    abstract val name: String
    abstract val lifeExpectancyYears: Int
}

data class Fish(
    override val _id: Id<Animal> = newId(),
    override val _type: String = Fish::class.java.simpleName,
    override val name: String,
    override val lifeExpectancyYears: Int,
    val deepSeaFish: Boolean,
): Animal()

fun main(args: Array<String>) {
    val client = KMongo.createClient()
    val database = client.getDatabase("test_kmongo_issue")
    val col = database.getCollection<Animal>()
    val fishInstance = Fish(name = "Lanternfish", lifeExpectancyYears = 8, deepSeaFish = true)
        .also { col.insertOne(it) }

    val fishInstanceAfterDeserialization = col.findOne(Animal::name eq fishInstance.name)
        ?: throw Exception("fish not found")

    println("Fish instance _id field is a ${fishInstance._id::class.java.simpleName}")
    println("Fish instance (after deserialization) _id field is a ${fishInstanceAfterDeserialization._id::class.java.simpleName}")

    if (fishInstance._id::class != fishInstanceAfterDeserialization._id::class) {
        println("It did not work properly :/")
    }
}

The output is:

Fish instance _id field is a WrappedObjectId
Fish instance (after deserialization) _id field is a StringId
It did not work properly :/

Is this the expected result for an example like this? I am having some issues in my project since it sometimes compares _id (which are supposed to be ObjectIds) against Strings.

Welcius avatar Mar 16 '21 16:03 Welcius

Hi Welcius,

technically I think that is not a bug, cause the document is serialized correctly cause you are adding a "Fish" Document to the collection and this is the correct BSON representation

if u need a fast solution (workaround) you can use a workaround: wrap it in AnimalContanier it will force the DB to specify the "__type" and you can safely cast it back

To hold the efficiency you can replicate the id in the container

see how I solved my analog problem image

image

image

note: `col.findOne(Animal::name eq fishInstance.name) should be changed

this is how I used find filter:

mode base via json structure: val filter = Document.parse("{ \"order.userId\": \"$userId\"}}") ordersCollection.find(filter)

mode 2 via obj type ordersCollection.find(OrderContainer::order / Order::creationTime gt from)

mixed: val filter = and( or( eq("order.___type", "takeaway"), eq("order.___type", "delivery") ), OrderContainer::order / Order::creationTime gt from, OrderContainer::order / Order::creationTime lt to ) ordersCollection.find(filter)

I hope this can help you!

I'm not a contributor of kmongo, but I'm using it daily, I hope you will correct me there if there is some misunderstanding

fscarponi avatar Mar 18 '21 09:03 fscarponi

Hi Welcius,

technically I think that is not a bug, cause the document is serialized correctly cause you are adding a "Fish" Document to the collection and this is the correct BSON representation

if u need a fast solution (workaround) you can use a workaround: wrap it in AnimalContanier it will force the DB to specify the "__type" and you can safely cast it back

To hold the efficiency you can replicate the id in the container

see how I solved my analog problem image

image

image

note: `col.findOne(Animal::name eq fishInstance.name) should be changed

this is how I used find filter:

mode base via json structure: val filter = Document.parse("{ \"order.userId\": \"$userId\"}}") ordersCollection.find(filter)

mode 2 via obj type ordersCollection.find(OrderContainer::order / Order::creationTime gt from)

mixed: val filter = and( or( eq("order.___type", "takeaway"), eq("order.___type", "delivery") ), OrderContainer::order / Order::creationTime gt from, OrderContainer::order / Order::creationTime lt to ) ordersCollection.find(filter)

I hope this can help you!

I'm not a contributor of kmongo, but I'm using it daily, I hope you will correct me there if there is some misunderstanding

Thank you for the workarounds, I appreciate them, but I do think that it is, in fact, a bug. Those workarounds may work, but you lose the typed reference, so they are not refactor resilient, and they are not a consistent solution to the undergoing problem, which needs to be solved.

The Id type should be able to infer the subtype of WrappedObjectId directly from the BSON representation of the document provided by the Mongo driver underneath it: as you can see someone reported it before me (in the issue I mentioned) and was thought to be solved since the author could not reproduce it. Fixing this bug is important, because it can cause weird situations for the developer such as KMongo not finding a document because it is comparing StringIds to ObjectIds, and those do not match.

You can also see the inconsistency if you add a new attribute which is an id to the model, and it will be deserialized as a WrappedObjectId, like it should be. For some reason, only the _id field deserializes as an StringId, and it is really an ObjectId in the document of the collection, of course.

Welcius avatar Mar 18 '21 11:03 Welcius

Thank you for reporting. The issue was fixed for kotlinx.serialization but not for jackson mapping. I'm going to commit a fix :)

zigzago avatar Mar 21 '21 17:03 zigzago