import org.bson.{ BSON, Transformer }import org.bson.types.Binarytrait CustomBinaryDataSerializer extends MongoConversionHelper {private val transformer = new Transformer {// Invoked by the Java driver whenever it encounters a type that has a registered encoding hookdef transform(o: AnyRef): AnyRef = o match {// I think there's a potential problem here WRT type erasure...case binary: Array[Byte] => new Binary(0, binary)case _ => o}}// Loads your hook into MongoDBoverride def register() = {BSON.addEncodingHook(classOf[Array[Byte]], transformer)super.register() // <-- this is important if you want to setup a chain of transformers in one declaration}override def unregister() = {BSON.removeEncodingHooks(classOf[[Array[Byte]])super.unregister()}}object CustomBinarySupport extends CustomBinaryDataSerializer {def apply() = {super.register()}}Then just run CustomBinarySupport() somewhere in your code to register the new encoder.You might also venture so far as to add a custom decoder using the Decoding hooks, which would try to be clever in the same way; I'm not sure if you can hook into get the binary type from the driver though (i'll look into it, that'd be a useful feature with the hooks).
On Wednesday, March 16, 2011 at 3:10 PM, Benjamin Darfler wrote:
We are storing some byte arrays in Mongo using Casbah. We are very
data size conscious so we are using Bson Binary type 0 instead of the
default type 2 that Casbah uses. I'm currently doing a map over our
DbObject and converting Array[Byte] to new Binary(0, Array[Byte]) but
I have to assume there is an Implicit somewhere that is doing the
conversion to new Binary(2, Array[Byte]). I wonder if there is an easy
way to override this or re implement it such that I get all the lovely
Implicit magic and don't need to iterate over all my objects before
saving them.