2016-11-25 60 views
0

我有一個用Scala編寫的應用程序來訪問Mongo數據庫,我可以在其中查詢和插入數據。Scala中的MongoDB編解碼器壞了?

然而,當我嘗試使用collection.distinct("user")我得到的錯誤:

Unknown Error org.bson.codecs.configuration.CodecConfigurationException: 
    Can't find a codec for class scala.runtime.Nothing$. 

做一些谷歌上搜索,我發現我需要指定的編解碼器後,所以我initalised的MongoClient一個:

val clusterSettings = ClusterSettings 
    .builder() 
    .hosts(scala.collection.immutable.List(new com.mongodb.ServerAddress(addr)).asJava) 
    .build() 

val settings = MongoClientSettings.builder() 
       .codecRegistry(MongoClient.DEFAULT_CODEC_REGISTRY) 
       .clusterSettings(clusterSettings) 
       .build() 

val mongoClient: MongoClient = MongoClient(settings) 

仍然沒有運氣,得到了同樣的錯誤。

我想我會需要做一個自定義的編解碼器as per this web page

class NothingCodec extends Codec[Nothing] { 
    override def encode(writer:BsonWriter, value:Nothing, encoderContext:EncoderContext)={} 
    override def decode(reader: BsonReader, decoderContext: DecoderContext): Nothing = { 
     throw new Exception 
    } 
    override def getEncoderClass(): Class[Nothing] = { 
     classOf[Nothing] 
    } 
} 

但是,這並不工作,也沒有意義,沒有什麼是不是一個有效的返回類型; there exist no instances of this type。 因此,這obekouly不工作與Unknown Error java.lang.Exception(顯然!)的新錯誤

我錯過了一些與Mongo Scala驅動程序?還是它剛剛壞了?

+0

或者你可以看看http://reactivemongo.org/ – cchantep

回答

1

使用文檔代替:

collection.distinct[Document]("user") 

// i.e. 

case class User(name: String, id: String) 

records.distinct[Document]("user") 
.toFuture() 
.map(_ map { doc => getUserFromBson(doc).get }) 

def getUserFromBson(doc: Document): Option[User] = { 
for { 
    name <- doc.get("name") map { x => x.asString().getValue } 
    id <- doc.get("id") map { x => x.asString().getValue } 
    }yield(User(name, id)) 
} 

希望這會有所幫助。