【问题标题】:How to create builder for $set operation in casbah?如何在 casbah 中为 $set 操作创建构建器?
【发布时间】:2014-08-10 20:03:02
【问题描述】:

我无法为 casbah 中的 $set 操作创建足够的构建器

例如,如果同时定义了用户名和语言,则此功能可以正常工作

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 字段之外的所有内容。

【问题讨论】:

    标签: mongodb scala casbah


    【解决方案1】:

    寻找基于纯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: _*))
      }
    

    【讨论】:

      猜你喜欢
      • 2021-01-27
      • 1970-01-01
      • 2011-01-25
      • 2015-08-12
      • 1970-01-01
      • 2022-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多