0

我想从 MongoDB 中放入一个“用户”类数据。find()方法不返回我想要的类型。

我有一段代码,我不知道如何使用它:

def findUser(username: String) : Option[User] =
  {
    var user:Option[User] = None
    val userToFind = MongoDBObject("username" -> username)
    users.findOne(userToFind).foreach { x =>
      user = Some(new User(x("username").toString,x("password").toString,x("firstname").toString, x("lastname").toString, true,2))
    }
    user
  }

如何使用我的结果放入我的对象参数?

这是我的对象用户:

class User (
  val username    : String,
  var password    : String,
  var firstname   : String,
  var lastname    : String,
  var isActivated : Boolean,
  val tenantId    : Int
             )
{}
4

1 回答 1

4

例如像这样:

def findUser(username: String): Option[User] = {
    val result = mongoCollUser.findOne(MongoDBObject("username"->username));
    result.map { user => toUser(user)  }
  }


  def toUser(dbObject:DBObject) : User = {
      User(dbObject.as[String]("username"),dbObject.as[String]("password"),dbObject.as[String]("firstname"),dbObject.as[String]("lastname"),dbObject.as[Boolean]("isActivated"),dbObject.as[Int]("tenantId"))
  }

case class User (
             val username    : String,
             var password    : String,
             var firstname   : String,
             var lastname    : String,
             var isActivated : Boolean,
             val tenantId    : Int
             )
于 2013-10-07T13:38:16.533 回答