Java 在play framework scala中获取数据

Java 在play framework scala中获取数据,java,mongodb,scala,playframework,Java,Mongodb,Scala,Playframework,我将play framework与scala一起使用,我想从mongodb数据库中获取数据。如何获取/返回与令牌和进入控制器相关的记录,而不是true/false。以下是我的模型中的代码: def registers(userId:String,token: String): Boolean = { val query = BSONDocument("token" -> token) val ret = Await.result(db.find(query).one[BSONDoc

我将play framework与scala一起使用,我想从mongodb数据库中获取数据。如何获取/返回与令牌和进入控制器相关的记录,而不是
true
/
false
。以下是我的模型中的代码:

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
  }
}

RobertUdah想说的是,您不是在存储BSONDocument,而是在存储一个模型,该模型最终将作为BSONDocument/JSONDocument存储在数据库中。不过,您可能不希望只返回一个BSONDocument,而是返回一个特定的模型。因此,您应该考虑创建作者和读者,以便将BSONDocument转换为用户(例如),反之亦然

因此,如果您使用reactivemongo作为驱动程序,您应该检查以下文档:

有一段是从数据库返回一个人的

但是如果您真的只想返回BSONDocument,那么它就是
db.find(query)。一个[BSONDocument]
将返回一个
Future[Option[BSONDocument]]
。因此
wait.result(db.find(query).一个[BSONDocument],25秒)
将返回一个
选项[BSONDocument]
。这意味着你的价值已经是你想要的结果。 如果要访问BSONDocument本身,可能需要进行一些模式匹配以提取它,例如:

ret match {
    case Some(document): //do something with your document
    case None: //The document was not found
}
db.find(query).one[BSONDocument].map{
    case Some(document): //Do the thing
    case None: //The document was not found
}
而不是只检查
if(ret.isDefined)

另一方面,如果你能避免使用wait,那就更好了!您可以直接与未来合作,并在地图中处理结果,例如:

ret match {
    case Some(document): //do something with your document
    case None: //The document was not found
}
db.find(query).one[BSONDocument].map{
    case Some(document): //Do the thing
    case None: //The document was not found
}
这意味着映射中的代码将在将来完成后立即执行。但我真的不知道你想做什么

因此,根据您的代码,如果您保持
等待
,您将得到如下结果:

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
  }
}

那么,你想退货什么?BSON文档?@RobertUdah:我想使用mongodbJust return ret的查询返回数据