4

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.

4

2 回答 2

3

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))
于 2018-08-31T11:45:49.133 回答
1

Opened a feature request in the mongodb bug tracker (https://jira.mongodb.org/browse/SCALA-294), which was answered by Ross Lawley. He suggests to change the conversion code (from case class to document) from

def toDocument(t: Test) = Document("foo" -> t.foo)

to something like

def toDocument(t: Test) = {
  val d = Document()
  t.foo.foreach{ value =>
    d + ("foo" -> value)
  }
  d
}
于 2017-03-07T10:32:34.440 回答