title: Reactivemongo serializing a map into a BSONDocument
body: <p>I defined <code>BSONDocumentWriter</code>s to map domain objects (case classes) to BSON documents to be persisted in MongoDB using the ReactiveMongo driver. Defining the writers is quite straight-forward for case classes (although tedious and error prone: I wish there was a Salat-like solution for that). However, I can't seem to be able to do the same for a <code>Map[String,Any]</code> (where the values can be of type numeric, date or string). I found a <a href="https://github.com/ReactiveMongo/ReactiveMongo/blob/master/driver/samples/BSON.scala" rel="nofollow">code example</a> that defines a generic writer (and reader) for a map:</p>
  
  <pre><code>implicit def MapWriter[V](implicit vw: BSONDocumentWriter[V]): BSONDocumentWriter[Map[String, V]] = 
    new BSONDocumentWriter[Map[String, V]] {
    def write(map: Map[String, V]): BSONDocument = {
      val elements = map.toStream.map { tuple =&gt;
        tuple._1 -&gt; vw.write(tuple._2)
      }
      BSONDocument(elements)
    }
  }
  </code></pre>
  
  <p>but this does not work if there's no implicit <code>BSONDocumentWriter</code> for the type <code>V</code>, i.e., the snippet:</p>
  
  <pre><code>BSONDocument(
    "_id" -&gt; "asd",
    "map" -&gt; MapWriter[Any].write(Map("x" -&gt; 1, "y" -&gt; "2"))
  )
  </code></pre>
  
  <p>does not compile:</p>
  
  <pre><code>could not find implicit value for parameter vw: reactivemongo.bson.BSONDocumentWriter[Any]
      "map" -&gt; MapWriter[Any].write(Map("x" -&gt; 1, "y" -&gt; "2"))
                        ^
  </code></pre>
  
  <p>I thought maybe the writer should write to a <code>BSONValue</code> instead of a <code>BSONDocument</code> so I modified the example as follows:</p>
  
  <pre><code>implicit def ValueMapWriter[V](implicit vw: BSONWriter[V, BSONValue]): BSONDocumentWriter[Map[String, V]] = 
    new BSONDocumentWriter[Map[String, V]] {
    def write(map: Map[String, V]): BSONDocument = {
      val elements = map.toStream.map {
        tuple =&gt;
          tuple._1 -&gt; vw.write(tuple._2)
      }
      BSONDocument(elements)
    }
  }
  </code></pre>
  
  <p>And to keep things simple, I tried to use <code>Int</code> as the value type but again, the snippet:</p>
  
  <pre><code>BSONDocument(
    "_id" -&gt; "asd",
    "map" -&gt; ValueMapWriter[Int].write(Map("x" -&gt; 1, "y" -&gt; 2))
  )
  </code></pre>
  
  <p>does not compile:</p>
  
  <pre><code>could not find implicit value for parameter vw: reactivemongo.bson.BSONWriter[Int,reactivemongo.bson.BSONValue]
      "map" -&gt; ValueMapWriter[Int].write(Map("x" -&gt; 1, "y" -&gt; 2))
                            ^
  </code></pre>
  
  <p>If the above had worked I could have used some base class as the value type and defined its implicit writer.</p>
  
  <p>I am not sure why this is happening and how I can solve it. Maybe I am missing something obvious? Ideas?</p>