我想从MongoDB中输入一个“User”类数据。 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
)
{}
答案 0 :(得分: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
)