2

I have a simple code for getting the port number from MongoDB. I use scala and the driver is of course casbah.

  def getPortNo : Int {
    val query = MongoDBObject("_id" -> "Store")
    val data  = coll.findOne(query)
    return data.get("port")
  }

Here my application only has one document that id is equal to "store".

but this is not resolved in IDE.

I have the same code for getting the version.

  def getVersion : String = {
    val query = MongoDBObject("_id" -> "Store")
    val data  = coll.findOne(query)
    return data.get("version").toString
  }

this works well.

I tried data.get("port").toString.toInt and It also does not work.

Can someone tell me how to do this. I think the problem here is the returning value in not either number or a string. what is the return type and how can I cast it into a number.

Sergey Passichenko
  • 6,920
  • 1
  • 28
  • 29
bula
  • 8,719
  • 5
  • 27
  • 44

1 Answers1

2

It depends on how you store "port" field. Try data.as[Number]("value").intValue(). It must work any number format.

And you should consider that findOne returns Option, so you can return Option too:

  def getPortNo : Option[Int] = {
    val query = MongoDBObject("_id" -> "Store")
    val data  = coll.findOne(query)
    data.map(_.as[Number]("port").intValue)
  }

Or use some default value:

  def getPortNo : Int = {
    val query = MongoDBObject("_id" -> "Store")
    val data  = coll.findOne(query)
    data.map(_.as[Number]("port").intValue).getOrElse(80)
  }
Sergey Passichenko
  • 6,920
  • 1
  • 28
  • 29