2015-07-10 2 views
0

Я работаю с платформой Play и ReactiveMongoDB. Я пытаюсь написать читателя и автора для моего класса Customer. Все это делается в файле models.scala в следующем порядке:Как использовать ReactiveMongoDB и doc.getAs со сложным объектом?

import reactivemongo.bson._ 


case class StreetAddressLine(
    id: Option[BSONObjectID], 
    StreetAddressLine: String, 
    creationDate: Option[DateTime], 
    updateDate: Option[DateTime]) 

object StreetAddressLine { 
    implicit object StreetAddressLineBSONReader extends BSONDocumentReader[StreetAddressLine] { 
    def read(doc: BSONDocument): StreetAddressLine = 
     StreetAddressLine(
     doc.getAs[BSONObjectID]("_id"), 
     doc.getAs[String]("StreetAddressLine").get, 
     doc.getAs[BSONDateTime]("creationDate").map(dt => new DateTime(dt.value)), 
     doc.getAs[BSONDateTime]("updateDate").map(dt => new DateTime(dt.value))) 
} 
} 



case class PrimaryAddress(
    id: Option[BSONObjectID], 
    StreetAddressLine: List[StreetAddressLine], 
    PrimaryTownName: String, 
    CountryISOAlpha2Code: String, 
    PostalCode: String, 
    PostalCodeExtensionCode: String, 
    TerritoryOfficialName: String, 
    TerritoryAbbreviatedName: String, 
    creationDate: Option[DateTime], 
    updateDate: Option[DateTime]) 

object PrimaryAddress { 
    implicit object PrimaryAddressBSONReader extends BSONDocumentReader[PrimaryAddress] { 
    def read(doc: BSONDocument): PrimaryAddress = 
     PrimaryAddress(
     doc.getAs[BSONObjectID]("_id"), //Mongos internal identifier 
     doc.getAs[List[StreetAddressLine]]("StreetAddressLine").get, 
     doc.getAs[String]("PrimaryTownName").get,   
     doc.getAS[String]("CountryISOAlpha2Code").get, 
     doc.getAS[String]("PostalCode").get,  
     doc.getAs[String]("PostalCodeExtensionCode").get, 
     doc.getAs[String]("TerritoryOfficialName").get,  
     doc.getAs[String]("TerritoryAbbreviatedName").get, 
     doc.getAs[BSONDateTime]("creationDate").map(dt => new DateTime(dt.value)), 
     doc.getAs[BSONDateTime]("updateDate").map(dt => new DateTime(dt.value))) 
    } 
} 

Но я получаю сообщение об ошибке

[error] C:\Users\xxxxx\git\oneid-scala\oneid-scala\app\models\models.scala:54: 
value getAS is not a member of reactivemongo.bson.BSONDocument 
[error]   doc.getAS[String]("CountryISOAlpha2Code").get, 
[error]   ^
[error] C:\Users\xxxxx\git\oneid-scala\oneid-scala\app\models\models.scala:55: 
value getAS is not a member of reactivemongo.bson.BSONDocument 
[error]   doc.getAS[String]("PostalCode").get, 
[error] 

следующие строки

doc.getAS[String]("PostalCode").get,  
doc.getAs[String]("PostalCodeExtensionCode").get, 

я решил добавьте авторов в

package models 

import org.jboss.netty.buffer._ 
import org.joda.time.DateTime 
import play.api.data._ 
import play.api.data.Forms._ 
import play.api.data.format.Formats._ 
import play.api.data.validation.Constraints._ 

import reactivemongo.bson._ 





case class StreetAddressLine(
    id: Option[BSONObjectID], 
    StreetAddressLine: String, 
    creationDate: Option[DateTime], 
    updateDate: Option[DateTime]) 

object StreetAddressLine { 
    implicit object StreetAddressLineBSONReader extends BSONDocumentReader[StreetAddressLine] { 
    def read(doc: BSONDocument): StreetAddressLine = 
     StreetAddressLine(
     doc.getAs[BSONObjectID]("_id"), 
     doc.getAs[String]("StreetAddressLine").get, 
     doc.getAs[BSONDateTime]("creationDate").map(dt => new DateTime(dt.value)), 
     doc.getAs[BSONDateTime]("updateDate").map(dt => new DateTime(dt.value))) 
} 
implicit object StreetAddressLineBSONWriter extends BSONDocumentWriter[StreetAddressLine] { 
    def write(streetAddressLine: StreetAddressLine): BSONDocument = 
     BSONDocument(
     "_id" -> streetAddressLine.id.getOrElse(BSONObjectID.generate), 
     "StreetAddressLine" -> streetAddressLine.StreetAddressLine, 
     "creationDate" -> streetAddressLine.creationDate.map(date => BSONDateTime(date.getMillis)), 
     "updateDate" -> streetAddressLine.updateDate.map(date => BSONDateTime(date.getMillis))) 
    } 

} 



case class PrimaryAddress(
    id: Option[BSONObjectID], 
    StreetAddressLine: List[StreetAddressLine], 
    PrimaryTownName: String, 
    CountryISOAlpha2Code: String, 
    PostalCode: String, 
    PostalCodeExtensionCode: String, 
    TerritoryOfficialName: String, 
    TerritoryAbbreviatedName: String, 
    creationDate: Option[DateTime], 
    updateDate: Option[DateTime]) 

object PrimaryAddress { 

implicit object PrimaryAddressBSONReader extends BSONDocumentReader[PrimaryAddress] { 
    def read(doc: BSONDocument): PrimaryAddress = 
    PrimaryAddress(
     doc.getAs[BSONObjectID]("_id"), 
     doc.getAs[String]("StreetAddressLine").get, 
     doc.getAs[String]("PrimaryTownName").get, 
     doc.getAs[String]("CountryISOAlpha2Code").get, 
     doc.getAs[String]("PostalCode").get, 
     doc.getAs[String]("PostalCodeExtensionCode").get, 
     doc.getAs[String]("TerritoryOfficialName").get, 
     doc.getAs[String]("TerritoryAbbreviatedName").get, 
     doc.getAs[BSONDateTime]("creationDate").map(dt => new DateTime(dt.value)), 
     doc.getAs[BSONDateTime]("updateDate").map(dt => new DateTime(dt.value))) 
} 


implicit object PrimaryAddressBSONWriter extends BSONDocumentWriter[PrimaryAddress] { 
    def write(primaryAddress: PrimaryAddress): BSONDocument = 
     BSONDocument(
     "_id" -> primaryAddress.id.getOrElse(BSONObjectID.generate), 
     "StreetAddressLine" -> primaryAddress.StreetAddressLine, 
     "PrimaryTownName" -> primaryAddress.PrimaryTownName, 
     "CountryISOAlpha2Code" -> primaryAddress.CountryISOAlpha2Code, 
     "PostalCode" -> primaryAddress.PostalCode, 
     "TerritoryOfficialName" -> primaryAddress.TerritoryOfficialName, 
     "TerritoryAbbreviatedName" -> primaryAddress.TerritoryAbbreviatedName, 
     "creationDate" -> primaryAddress.creationDate.map(date => BSONDateTime(date.getMillis)), 
     "updateDate" -> primaryAddress.updateDate.map(date => BSONDateTime(date.getMillis))) 
    } 



} 

И ошибка компиляции изменилась к следующему

[info] Compiling 2 Scala sources to C:\Users\xxxxx\git\oneid-scala\oneid-scala 
\target\scala-2.11\classes... 
[error] C:\Users\xxxxx\git\oneid-scala\oneid-scala\app\models\models.scala:62: 
type mismatch; 
[error] found : String 
[error] required: List[models.StreetAddressLine] 
[error] Note: implicit object PrimaryAddressBSONWriter is not applicable here b 
ecause it comes after the application point and it lacks an explicit result type 

[error]  doc.getAs[String]("StreetAddressLine").get, 
[error]            ^
[error] one error found 
[error] (compile:compileIncremental) Compilation failed 
[error] Total time: 4 s, completed Jul 11, 2015 12:40:20 PM 
+0

Если вы посмотрите на [документации] (http://reactivemongo.org/releases/0.11/documentation/bson/typeclasses.html), вы бы увидели, как определять читателей/писателей для ваших собственных типов. Невозможно определить читатель, анализирующий свойство, тип которого (там «PrimaryAddress') ранее не предоставлялся как читатель. – cchantep

+0

cchantep спасибо. Я изменил код выше, чтобы включить определение для читателя для включенного настраиваемого класса StreetAddressLine, но он по-прежнему вызывает ошибку. Что мне не хватает? – pitchblack408

+0

Проверить сообщение компиляции – cchantep

ответ

1

Спасибо cchantep, следующий код компилируется в настоящее время. Я обнаружил, что здесь есть две части.

A. Чтобы иметь встроенные пользовательские классы в другом классе, каждый класс должен быть определен.

B. Оба писателя и читатели должны быть определены для всех классов или будут ошибки компилятора. Вы не можете просто определить читателей без писателей.

Следующий код компилируется нормально

package models 

import org.jboss.netty.buffer._ 
import org.joda.time.DateTime 
import play.api.data._ 
import play.api.data.Forms._ 
import play.api.data.format.Formats._ 
import play.api.data.validation.Constraints._ 

import reactivemongo.bson._ 





case class StreetAddressLine(
    id: Option[BSONObjectID], 
    StreetAddressLine: String, 
    creationDate: Option[DateTime], 
    updateDate: Option[DateTime]) 

object StreetAddressLine { 
    implicit object StreetAddressLineBSONReader extends BSONDocumentReader[StreetAddressLine] { 
    def read(doc: BSONDocument): StreetAddressLine = 
     StreetAddressLine(
     doc.getAs[BSONObjectID]("_id"), 
     doc.getAs[String]("StreetAddressLine").get, 
     doc.getAs[BSONDateTime]("creationDate").map(dt => new DateTime(dt.value)), 
     doc.getAs[BSONDateTime]("updateDate").map(dt => new DateTime(dt.value))) 
} 
implicit object StreetAddressLineBSONWriter extends BSONDocumentWriter[StreetAddressLine] { 
    def write(streetAddressLine: StreetAddressLine): BSONDocument = 
     BSONDocument(
     "_id" -> streetAddressLine.id.getOrElse(BSONObjectID.generate), 
     "StreetAddressLine" -> streetAddressLine.StreetAddressLine, 
     "creationDate" -> streetAddressLine.creationDate.map(date => BSONDateTime(date.getMillis)), 
     "updateDate" -> streetAddressLine.updateDate.map(date => BSONDateTime(date.getMillis))) 
    } 

} 



case class PrimaryAddress(
    id: Option[BSONObjectID], 
    StreetAddressLine: List[StreetAddressLine], 
    PrimaryTownName: String, 
    CountryISOAlpha2Code: String, 
    PostalCode: String, 
    PostalCodeExtensionCode: String, 
    TerritoryOfficialName: String, 
    TerritoryAbbreviatedName: String, 
    creationDate: Option[DateTime], 
    updateDate: Option[DateTime]) 

object PrimaryAddress { 

implicit object PrimaryAddressBSONReader extends BSONDocumentReader[PrimaryAddress] { 
    def read(doc: BSONDocument): PrimaryAddress = 
    PrimaryAddress(
     doc.getAs[BSONObjectID]("_id"), 
     doc.getAs[List[StreetAddressLine]]("StreetAddressLine").get, 
     doc.getAs[String]("PrimaryTownName").get, 
     doc.getAs[String]("CountryISOAlpha2Code").get, 
     doc.getAs[String]("PostalCode").get, 
     doc.getAs[String]("PostalCodeExtensionCode").get, 
     doc.getAs[String]("TerritoryOfficialName").get, 
     doc.getAs[String]("TerritoryAbbreviatedName").get, 
     doc.getAs[BSONDateTime]("creationDate").map(dt => new DateTime(dt.value)), 
     doc.getAs[BSONDateTime]("updateDate").map(dt => new DateTime(dt.value))) 
} 



implicit object PrimaryAddressBSONWriter extends BSONDocumentWriter[PrimaryAddress] { 
    def write(primaryAddress: PrimaryAddress): BSONDocument = 
     BSONDocument(
     "_id" -> primaryAddress.id.getOrElse(BSONObjectID.generate), 
     "StreetAddressLine" -> primaryAddress.StreetAddressLine, 
     "PrimaryTownName" -> primaryAddress.PrimaryTownName, 
     "CountryISOAlpha2Code" -> primaryAddress.CountryISOAlpha2Code, 
     "PostalCode" -> primaryAddress.PostalCode, 
     "TerritoryOfficialName" -> primaryAddress.TerritoryOfficialName, 
     "TerritoryAbbreviatedName" -> primaryAddress.TerritoryAbbreviatedName, 
     "creationDate" -> primaryAddress.creationDate.map(date => BSONDateTime(date.getMillis)), 
     "updateDate" -> primaryAddress.updateDate.map(date => BSONDateTime(date.getMillis))) 
    } 



} 
+0

У меня была аналогичная проблема, и я смог сделать ее компилируемой с использованием этого ответа. Однако, похоже, что читатели и писатели на самом деле не называются во время работы. Есть идеи? – redwulf

Смежные вопросы