Reputation: 1654
I am having a hard time trying to create my BSON reader/writer on play 2.1.5 with mongodb.
Here is a code excerpt in app/model/Boat.scala :
implicit object BoatBSONReader extends BSONDocumentReader[Boat] {
def read(doc: BSONDocument): Boat =
Boat(
(...)
doc.getAs[Accomodation]("accomodation").get,
(...)
)
}
Then in app/model/Accomodation.scala i have :
case class Accomodation(number_cabins: Int, cabin_configuration: Option[String], bed_configuration: Option[String], number_guest: Int)
(...)
implicit object AccomodationBSONReader extends BSONDocumentReader[Accomodation] {
def read(doc: BSONDocument): Accomodation =
Accomodation(
doc.getAs[Int]("number_cabins").get,
doc.getAs[String]("cabin_configuration"),
doc.getAs[String]("bed_configuration"),
doc.getAs[Int]("number_guest").get)
}
}
I am using the "Option[String]" on some field because those keys can be missing from mongodb record. In which case i would like to return en empty value in my scala object.
This is causing this error at compile time :
[NoSuchElementException: None.get]
doc.getAs[Accomodation]("accomodation").get,
Maybe someone will point me to the right direction.
Thanx !
Upvotes: 0
Views: 815
Reputation: 11479
This is not a compile time error, it is a runtime error that means that a document you are trying to deserialize as a Boat is not readable with your readers.
This could either be that there is no field "accomodation" in the document or that it has a value that could not be deserialized to an instance of Accomodation with your Accomodation reader. This leads to getAs[A](name)
returning None
.
Calling .get
on None
gives you a NoSuchElementException
in general it is considered bad practice to ever call .get on Options, instead you should always handle the two possible choices. You can read more about how Option works here for example: http://danielwestheide.com/blog/2012/12/19/the-neophytes-guide-to-scala-part-5-the-option-type.html
You could possibly get more info about what is wrong by using BSONDocument.getAsTry[A](name)
instead, as that returns either Success
or Fail
where Fail
might preserve details about the error.
Upvotes: 1