Search code examples
mongodbscalamongo-scala-driver

Not persisting Scala None's instead of persisting as null value


I noticed that the scala driver (version 1.2.1) writes Option values of None as null to the corresponding field. I would prefer omitting the fieid completely in this case. Is this possible?

Example

case class Test(foo: Option[String])
persist(Test(None))

leads to

> db.test.find()
{ "_id": "...", "foo": null }

but I want to achieve

> db.test.find()
{ "_id": "..." }

When I used casbah, I think my intended behaviour was the default.


Solution

  • http://mongodb.github.io/mongo-scala-driver/2.4/bson/macros/

    Now you can use macros for it:

    val testCodec = Macros.createCodecProviderIgnoreNone[Test]()
    

    and in codec conf:

    lazy val codecRegistry: CodecRegistry = fromRegistries(fromProviders(testCodec))