Search code examples
scalacasbah

Scala and Casbah - error: Option[com.mongodb.DBObject] does not take parameters


I'm trying to fetch doc and get it's attribute. When I use findOne method, I expect to get MongoDBObject, but I receive Option[com.mongodb.DBObject]. How to get an attribute from it? Is it possible to get MongoDBObject instead of this?

scala> var col = MongoClient()("test")("counters")
col: com.mongodb.casbah.MongoCollection = MongoCollection({ "_id" : "some" , "value" : 0})

scala> var doc = col.findOne()
doc: Option[com.mongodb.DBObject] = Some({ "_id" : "some" , "value" : 0})

scala> doc("_id")
<console>:13: error: Option[com.mongodb.DBObject] does not take parameters
              doc("_id")
                 ^
scala>

Solution

  • Casbah API doesn't know the contents of your database and cannot be sure that record you are asking for really exists. In Java such method would simply return object that can be null. This is discouraged in Scala in faviour of safer Option[T] type. This way you are forced to handle a situation where object didn't exist. You have several syntaxes for that (from worst to best:

    When you are sure object is there - otherwise exception will be thrown

    col.findOne().get
    

    When you want to handle both cases:

    col.findOne() match {
      case Some(r) => //r is your record
      case None => //record didn't exist
    }
    

    When you want to perform certain operations on your record (monadic style)

    col.findOne().map(r => r("_id")).foreach(println)
    

    The code above will print the _id column only if such record was found - and do nothing otherwise.