0

I can't create adequate builder for $set operation in casbah

For example this function work properly, if both username and lang are defined

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)
}

I try to build update dynamically, but cant find a proper way. Something like this:

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)
}

kills everithing except id, username and lang fields.

vdshb
  • 1,949
  • 2
  • 28
  • 40

1 Answers1

0

Find simple solution based on pure 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: _*))
  }
vdshb
  • 1,949
  • 2
  • 28
  • 40