简体   繁体   中英

Get data in play framework scala

I'm using play framework with scala and I want to fetch data from mongodb database. How can I get/return records instead of true / false , related with token and get in controller. Here is my code in my model:

def registers(userId:String,token: String): Boolean = {
  val query = BSONDocument("token" -> token)
  val ret = Await.result(db.find(query).one[BSONDocument], 25.seconds)
  if(ret.isDefined){
    true
  } else{
    false
  }
}

What RobertUdah try to say is that you are not storing BSONDocument, you are storing a model that will be in the end stored as a BSONDocument/JSONDocument in the database. Still what you may want is not returning just a BSONDocument but a specific model. So you should think about creating writers and readers in order to transform your BSONDocument to a User (for example) and vice versa.

So if you are using reactivemongo as the driver you should check the doc: http://reactivemongo.org/releases/0.12/documentation/tutorial/find-documents.html

There's a paragraph where a Person is returned from the database.

But if you really want to return just the BSONDocument the thing is db.find(query).one[BSONDocument] will return a Future[Option[BSONDocument]] . So Await.result(db.find(query).one[BSONDocument], 25.seconds) will return an Option[BSONDocument] . This means your value ret is already the result you are looking for. If you want to access the BSONDocument itself, you should maybe do some pattern matching to extract it for example:

ret match {
    case Some(document): //do something with your document
    case None: //The document was not found
}

Instead of just checking if (ret.isDefined) .

On a side note, if you can avoid using Await it would be better! You could work directly with a future and do your processing of the result in a map, for example:

db.find(query).one[BSONDocument].map{
    case Some(document): //Do the thing
    case None: //The document was not found
}

This means the code inside the map will be executed as soon as the future is done. But I don't really know what you are trying to do.

So based on your code if you keep the Await you would end up with something like:

def registers(userId:String,token: String): Boolean = {
  val query = BSONDocument("token" -> token)
  val ret = Await.result(db.find(query).one[BSONDocument], 25.seconds)
  ret match {
    case Some(doc): //Process it
        true
    case None: //Do something else
        false
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM