我正在尝试编写一个查询,以使用Casbah通过对象ID查找,这似乎很简单,但是...我找不到。
我尝试了这个:
def get(id: Option[String]): User = {
val mongoDB : MongoDB = MongoConnection().apply("test")
val mongoColl : MongoCollection = mongoDB.apply("users")
val objectId = id.getOrElse().asInstanceOf[String]
val o : DBObject = MongoDBObject("_id" -> objectId)
val u = mongoColl.findOne(o)
val user = new User()
for(x <- u){
user.id = x.getAs[String]("_id")
user.username = x.getAs[String]("username")
user.password = x.getAs[String]("password")
}
user
}
还有这个:
def get(id: Option[String]): User = {
val mongoDB : MongoDB = MongoConnection().apply("test")
val mongoColl : MongoCollection = mongoDB.apply("users")
val objectId = "ObjectId(\"" +id.getOrElse().asInstanceOf[String] + "\")"
val o : DBObject = MongoDBObject("_id" -> objectId)
val u = mongoColl.findOne(o)
val user = new User()
for(x <- u){
user.id = x.getAs[String]("_id")
user.username = x.getAs[String]("username")
user.password = x.getAs[String]("password")
}
user
}
编译并运行,但没有结果。
我也尝试过这个:
def get(id: Option[String]): User = {
val mongoDB : MongoDB = MongoConnection().apply("test")
val mongoColl : MongoCollection = mongoDB.apply("users")
val objectId : ObjectId = id.getOrElse().asInstanceOf[ObjectId]
val o : DBObject = MongoDBObject("_id" -> objectId)
val u = mongoColl.findOne(o)
val user = new User()
for(x <- u){
user.id = x.getAs[String]("_id")
user.username = x.getAs[String]("username")
user.password = x.getAs[String]("password")
}
user
}
但是,由于String无法转换为ObjectId,因此无法编译。
java.lang.ClassCastException: java.lang.String cannot be cast to org.bson.types.ObjectId
谢谢您的帮助 :)
最佳答案
“ _id”通常作为对象ID存储在MongoDB中,而不是字符串中存储。字符串和对象ID是不同的类型,您不能将字符串转换为对象ID。 ObjectId在MongoDB中也是一个独特的类型,因此ObjectId(“ abcdefgh123”)与字符串“ abcdefgh123”不同。
您需要在Casbah中按ObjectID搜索。尝试以下方法:
def get(id: Option[ObjectId]): User = {
val mongoDB : MongoDB = MongoConnection().apply("test")
val mongoColl : MongoCollection = mongoDB.apply("users")
val objectId : ObjectId = id.getOrElse().asInstanceOf[ObjectId]
id.foreach( oid => {
val o : DBObject = MongoDBObject("_id" -> oid)
val u = mongoColl.findOne(o)
val user = new User()
for(x <- u){
user.id = x.getAs[ObjectId]("_id")
user.username = x.getAs[String]("username")
user.password = x.getAs[String]("password")
}
user
})
}