Play 2/Scala-通用反应式Mongo CRUD-json序列化
我发现一些问题与我的问题非常接近,但它们并没有解决我的问题 我试图实现的是对我的CRUD DAO的抽象,用于常见的CRUD操作 我为此构建了一个GenericMongoDataActor:Play 2/Scala-通用反应式Mongo CRUD-json序列化,json,scala,playframework-2.0,crud,reactivemongo,Json,Scala,Playframework 2.0,Crud,Reactivemongo,我发现一些问题与我的问题非常接近,但它们并没有解决我的问题 我试图实现的是对我的CRUD DAO的抽象,用于常见的CRUD操作 我为此构建了一个GenericMongoDataActor: abstract class GenericMongoDaoActor[T <: Entity: Writes](implicit inj:Injector, implicit val f:Format[T]) extends Actor with Injectable { protected va
abstract class GenericMongoDaoActor[T <: Entity: Writes](implicit inj:Injector, implicit val f:Format[T]) extends Actor with Injectable {
protected val db = inject[DefaultDB]
protected val collectionName: String
protected val collection:JSONCollection
//set to None to use fallback
def defaultSelector(obj:T):Option[JsObject] = None
def fallbackSelector(obj:T) = Json.obj("_id" -> Json.obj("$elemMatch" -> obj._id))
protected def find(jsObject: JsObject) = {
val currentSender = sender
val futureOption = collection
.find(jsObject)
.cursor[T](ReadPreference.primaryPreferred)
.headOption
futureOption.mapTo[Option[T]].flatMap {
case Some(pobj) =>
currentSender ! Some(pobj)
Future{pobj}
case None =>
currentSender ! None
Future{None}
}
}
protected def save(obj:T):Unit = {
update(obj, true)
}
protected def update(obj:T):Unit = {
update(obj, false)
}
private def update(obj:T, upsert: Boolean):Unit = {
val selector = defaultSelector(obj) match {
case None => fallbackSelector(obj)
case Some(sel) => sel
}
collection.update(
selector,
obj,
GetLastError.Default,
upsert).onComplete {
case Failure(e) => Logger.error("[" + this.getClass.getName + "] Couldn`t update " + obj.getClass.getName + ": " + Json.prettyPrint(Json.toJson(obj)), e)
case Success(lastError) => //currentSender ! lastError todo: do something with lastError
}
}
def findAll() = {
collection.find(Json.obj()).cursor[T](ReadPreference.primaryPreferred).collect[List]()
}
}
当前有2个类继承实体
正如您所看到的,我的DOAActor已经绑定到上下文以查找范围中的写入[T]
abstract class GenericMongoDaoActor[T <: Entity: Writes]
抽象类genericmongodoactor[T当我从早期版本的ReactiveMongo迁移时,我遇到了类似的问题。对我有效的方法是在对ReactiveMongo API的各种调用中进行一些.as[JsObject]
转换
因此,如果在我之前:
collection.update(
selector,
obj,
...
)
我将其替换为:
collection.update(
selector,
obj.as[JsObject],
...
)
这似乎足够了,尽管我以稍微不同的方式向您提供了必要的JSON转换器;我的抽象类的子类必须实现隐式val fmt:Format[T]
成员。我怀疑这是否重要,但这似乎是一种行之有效的方法:-)您需要使用OWrite和OFormat,而不是write和Format。
我知道OWrites扩展了写操作和OFormat扩展格式,但是您使用的reactivemongo版本正在等待OWrites和OFormat,而不是它的超级类型。这解决了我的问题。非常感谢。我仍然不明白为什么它抱怨它需要在上面使用OWrites或OFormat。Writes
而不是OWrites
,因为编写与预期BSON文档对应的结构的特殊性必须使用JsObject
,而不是JsValue
(写入的结果)。@cchantep I说“使用OWrites而不是Writes”。使用.as[JsObject]是一个黑客,不是一个解决方案。play reactivemongo的最新版本使用了OWrites、OFormat等。我也有同样的错误。请阅读错误。
collection.update(
selector,
obj,
...
)
collection.update(
selector,
obj.as[JsObject],
...
)