MongoDB Scala驱动程序-呈现BSON文档 [英] MongoDB Scala Driver - Rendering BSON Documents

查看:192
本文介绍了MongoDB Scala驱动程序-呈现BSON文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们目前正在使用一种类型安全的查询语言,该自定义DSL允许我们轻松编写数据库查询,这些查询将被解释并转换为Mongo Queries.

We currently have a Type-Safe query language at work, this custom DSL allows us to easily write database queries that are interpreted and converted into Mongo Queries.

我们最近从Casbah换成了新的Mongo Scala驱动程序,并改写了我们的翻译.但是,在处理可选值时遇到一些问题.

We recently swapped over from Casbah to the new Mongo Scala Driver and rewrote our interpreter. I am however having some issues when dealing with optional values.

这是一个示例查询:

dao.headOption(Order.id === orderId.some)

订单对象上存储的类型是一个选项,因此我们也将提供的ID提升为一个选项.但是,每当我尝试以以下方式呈现用于调试以及测试用例的生成查询时:

The type stored on the Order Object is an Option so we lift the provided id into an option as well. However whenever I try to render out the generated query for debugging as well as for test cases in the following manner:

import org.mongodb.scala.bson.{BsonDocument, codecs}

query.toBsonDocument(BsonDocument.getClass, codecs.DEFAULT_CODEC_REGISTRY)

以下异常最终被抛出:

Can't find a codec for class scala.Some.
org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class scala.Some.

我不确定如何纠正此问题,或者我不确定是否需要为Option实现我自己的编解码器,如果我这样做,我也不知道该怎么做.

I am not sure how to rectify this, or if I need to implement my own codec for Options, and if I do I have no idea how I would do that.

任何帮助将不胜感激. 预先谢谢你

Any help would be gladly appreciated. Thank you in advance

更新

我已经看到我可以尝试实现编解码器接口,如下所示:

I have seen that I can try and implement the Codec Interface as shown here:

http://mongodb.github.io/mongo- java-driver/3.0/bson/codecs/

我是否需要为Option的每种可能的子类型实现它?

Would I need to implement it for each possible sub-type of Option?

示例Option [Int],Option [UUID],Option [List [String]]等

Example Option[Int], Option[UUID], Option[List[String]] etc.

推荐答案

您可以使用类似的方法来解决此问题

you could use something like this to fix the issue

class SomeCodec extends Codec[Some[_]] {
  override def encode(writer: BsonWriter, value: Some[_], encoderContext: EncoderContext): Unit = value match {
    case Some(v: String) ⇒ writer.writeString(v)
    case Some(v: Int) ⇒ writer.writeInt32(v)
    case Some(v: Long) ⇒ writer.writeInt64(v)
    case Some(v: Boolean) ⇒ writer.writeBoolean(v)
  }

  override def getEncoderClass: Class[Some[_]] = classOf[Some[_]]

  override def decode(reader: BsonReader, decoderContext: DecoderContext): Some[_] = {
    reader.getCurrentBsonType match {
      case BsonType.BOOLEAN ⇒ Some(reader.readBoolean())
      case BsonType.STRING ⇒ Some(reader.readString())
      case BsonType.INT64 ⇒ Some(reader.readInt64())
      case BsonType.INT32 ⇒ Some(reader.readInt32())
    }
  }
}

这篇关于MongoDB Scala驱动程序-呈现BSON文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆