writeSafe

abstract fun <T> writeSafe(name: String, obj: T, type: KType)(source)
inline fun <T> writeSafe(name: String, obj: T)(source)

Writes an arbitrary obj into a BSON document.

All nested values are escaped as necessary such that the result is a completely inert BSON document.

Serialization configuration

This method uses the serialization methods configured in the BsonFactory that created this instance.

For example, if you use the official Java or Kotlin MongoDB drivers, this method will use your configured CodecRegistry.

Example

data class User(
val _id: ObjectId,
val profile: Profile,
)

data class Profile(
val name: String,
val age: Int?,
)

val factory: BsonFactory = …

val bson = factory.buildDocument {
writeSafe("user", User(ObjectId("69c93e17b96e83b72d11b734"), Profile("Bob", 30)))
}

val user = bson.decode<User>()

println(user._id) // ObjectId(69c93e17b96e83b72d11b734)
println(user.profile.name) // Bob
println(user.profile.age) // 30