Deletion in 1 to M relationship collection.

38 views
Skip to first unread message

Saurav Jha

unread,
Nov 28, 2020, 9:14:48 PM11/28/20
to kmongo
I have two collection:
data class Product(
@Contextual
@SerialName("_id") val _id: Id<Product> = newId(),
val name: String,
val description: String,
val price: Double,
val deliveryPrice: Double
)

and 
data class ProductOption(
@Contextual
@SerialName("_id") val _id: Id<ProductOption>? = newId(),
val name: String,
val description: String,
val productId: Id<Product>
)

There is 1: M relationship between the two collection as shown in the data class. And want to delete given  ProductOption for a specific product. 

val deletedResult = runBlocking {
prodCol.findOneById(ObjectId("5fc2e2a041aab268eead535e"))?.also {
prodOptionCol.deleteOne(and (ProductOption::_id eq ObjectId("5fc2e89c2f48cb220c7f9da2"), ProductOption::productId eq it._id ))
}
} 
"eq" operator does not work when comparing the _id for the production option. Could not find an example where we can compare the org.bson.types.ObjectId. 
Is there a better way to do it. 
Any help will be appreciated .

Kind Regards,
Saurav Jha

zigzago

unread,
Nov 29, 2020, 4:39:38 AM11/29/20
to kmongo
Hello,

You may hit this bug https://github.com/Litote/kmongo/issues/249 (that will be fixed soon)
 
Workaround:

val deletedResult = runBlocking {
prodCol.findOneById(ObjectId("5fc2e2a041aab268eead535e"))?.also {
prodOptionCol.deleteOne(and (ProductOption::_id eq ObjectId("5fc2e89c2f48cb220c7f9da2"), ProductOption::productId eq WrappedObjectId(it._id.toString()) ))
}
}

HTH

zigzago

unread,
Nov 29, 2020, 5:24:32 AM11/29/20
to kmongo
Or if the question is about comparing an ObjectId to an Id, you can use the toId() extension:

import org.litote.kmongo.id.toId()

val deletedResult = runBlocking {
prodCol.findOneById(ObjectId("5fc2e2a041aab268eead535e"))?.also {
prodOptionCol.deleteOne(and (ProductOption::_id eq ObjectId("5fc2e89c2f48cb220c7f9da2").toId(), ProductOption::productId eq it._id ))
}
}

HTH
Reply all
Reply to author
Forward
0 new messages