我无法为casbah中的$ set操作创建足够的构建器
例如,如果定义了username和lang,则此函数可以正常工作
def updateUser(userId: String, username: Option[String], lang: Option[String]) = {
val updatedUser = MongoDBObject("_id" -> new ObjectId(userId))
val update = $set("username" -> username.get, "lang" -> lang.get)
usersCollection.update(updatedUser, update)
}
我尝试动态构建更新,但无法找到正确的方法。像这样:
def updateUser(userId: String, username: Option[String], lang: Option[String]) = {
val updatedUser = MongoDBObject("_id" -> new ObjectId(userId))
val updateBuilder = new MongoDBObjectBuilder()
if (username.isDefined)
updateBuilder += "username" -> username.get
if (lang.isDefined)
updateBuilder += "lang" -> lang.get
val update = updateBuilder.result()
if (username.isDefined || lang.isDefined)
usersCollection.update(updatedUser, update)
}
除了id,username和lang字段外,杀死了。
答案 0 :(得分:0)
找到基于纯scala的简单解决方案
def updateUser(userId: String, username: Option[String], lang: Option[String]) = {
val updatedUser = MongoDBObject("_id" -> new ObjectId(userId))
var update = Seq[(String, String)]()
if (username.isDefined) update = update :+ ("username" -> username.get)
if (lang.isDefined) update = update :+ ("lang" -> lang.get)
if (username.isDefined || lang.isDefined)
usersCollection.update(updatedUser, $set(update: _*))
}