我有以下课程:
case class DeviceRegistration(deviceData: DeviceData,
pin: String,
created: DateTime) {}
类型DeviceData
简单地定义为4个字符串字段。
我一直试图将一种DeviceRegistration
插入到mongo集合中失败。我想确保日期存储为ISODate而不是NumberLong,因此我实现了自定义读者和编写者。
implicit object DeviceDataWriter extends BSONDocumentWriter[DeviceData] {
def write(data: DeviceData): BSONDocument = BSONDocument(
DEVICE_ID_KEY -> data.deviceId,
MODEL_KEY -> data.model,
BRAND_KEY -> data.brand,
MANUFACTURER_KEY -> data.manufacturer)
}
implicit object DeviceRegistrationWriter extends BSONDocumentWriter[DeviceRegistration] {
def write(registration: DeviceRegistration): BSONDocument = BSONDocument(
DEVICE_DATA_KEY -> registration.deviceData,
PIN_KEY -> registration.pin,
CREATED_KEY -> BSONDateTime(registration.created.getMillis))
}
implicit object DeviceDataReader extends BSONDocumentReader[DeviceData] {
def read(doc: BSONDocument): DeviceData = {
val deviceId = doc.getAs[String](DEVICE_ID_KEY).get
val model = doc.getAs[String](MODEL_KEY)
val brand = doc.getAs[String](BRAND_KEY)
val manufacturer = doc.getAs[String](MANUFACTURER_KEY)
DeviceData(deviceId, model, brand, manufacturer)
}
}
implicit object DeviceRegistrationReader extends BSONDocumentReader[DeviceRegistration] {
def read(doc: BSONDocument): DeviceRegistration = {
val deviceData = doc.getAs[DeviceData](DEVICE_DATA_KEY).get
val pin = doc.getAs[String](PIN_KEY).get
val created = doc.getAs[BSONDateTime](CREATED_KEY).map(dt => new DateTime(dt.value))
DeviceRegistration(deviceData, pin, created.get)
}
}
我正在尝试使用以下代码插入文档:
def save(deviceRegistration: DeviceRegistration): Future[DeviceRegistration] = {
deviceRegistrations.insert(deviceRegistration).map(result => deviceRegistration)
}
要检索,我这样做:
def findDeviceRegistrationRequest(deviceConfirmationData: DeviceConfirmationData) = {
deviceRegistrations.find(BSONDocument("pin" -> deviceConfirmationData.pin))
.one[DeviceRegistration](ReadPreference.Primary)
}
记录存储如下:
{ "_id" : ObjectId("56dea8d0d8cadd6ff70690d8"), "deviceData" : { "deviceId" : "kdsajkldjsalkda" }, "pin" : "9914", "created" : NumberLong("1457432783921") }
创作日期显然没有被我的作者序列化。似乎reactivemongo正在使用一些默认编写器。
同样,当我阅读时,我得到一个例外:
Caused by: java.lang.RuntimeException: (/created,List(ValidationError(List(error.expected.date),WrappedArray())))
所以它显然也没有使用我的读者。
我没有任何运气谷歌搜索。我错过了什么?
我也试图找到一种方法来专门设置我想要使用的编写器和阅读器(而不是依赖于隐式机制),但我无法弄明白。
任何指向正确方向的人都会非常感激。