如何使用Scala更新CouchDB中的文档

时间:2016-10-25 10:42:15

标签: scala couchdb

我想使用优秀的Scala客户端CouchDB-Scala更改CouchDB数据库中的文档。

我知道文档的ID,我准备好了新数据。举个例子,假设我的数据就是这个案例类:

case class Person (name: String, age: Int)

我想按照

的方式做点什么
val newData = Person("new name", 56)
val docId = "4e5720837e3c057facbaa4e68b01a787"
update(newData, docId)

1 个答案:

答案 0 :(得分:1)

这对我有用:

import com.ibm.couchdb._
import scala.concurrent.duration._

def update(newData: Person, docId: String) = {

  val docs = dbApi.docs

  val updateActions = for {
    oldDoc <- docs.get[Person](docId)
    newDoc = oldDoc.copy(doc = newData)
    updateResult <- docs.update(newDoc)

  } yield updateResult

  val timeoutLength = Duration.create(15, SECONDS) 
  updateActions.unsafePerformSyncAttemptFor(timeoutLength)
}

此处dbApi也执行数据库设置:

import scalaz.concurrent.Task
import scalaz.{-\/, \/, \/-}

val dbApi = {
  val couchDbHostName = "couchDbForMyApp"
  val couch = CouchDb(couchDbHostName, 5984)
  // Define a type mapping used to transform class names into the doc kind
  val typeMapping = TypeMapping(classOf[Person] -> "Person")
  val dbName = "myApp-database"

  // Trying to create a database with the same name as an existing one results in an error
  createDatabaseIfItDoesntExistSync(dbName, couch)

  // Return an instance of the DB API by name and type mapping
  couch.db(dbName, typeMapping)
}

def await[T](future: Task[T]): Throwable \/ T = future.unsafePerformSyncAttempt

def createDatabaseIfItDoesntExistSync(dbName: String, couch: CouchDb) = {
  val db = couch.dbs.get(dbName)
  await(db) match {
    case -\/(e) =>
      println(s"Creating database $dbName")
      await(couch.dbs.create(dbName))

    case \/-(existingDb) =>
      println(s"Database with name $dbName already existed")
  }
}

我总是很乐意为代码改进提供建议!