简体   繁体   English

插入数据库后,scala salat objectid发生更改

[英]scala salat objectid is changing after inserting into database

I've a problem with Salat library in scala - I've got a case class Item: 我在Scala的Salat库遇到问题-我有一个案例类项目:

case class Item(_id: ObjectId = new ObjectId, var name: String, var active: Boolean) extends WithId {
  override def id: Option[ObjectId] = Some(_id)
}

The _id field is created upon Item instantiation. _id字段是在Item实例化时创建的。

I'm trying to test the functionality of inserting an Item as follows: 我正在尝试测试插入项目的功能,如下所示:

  var itemObj = Item(name = "testItem", active = true)

  "MainService" should {
    "put an item into database" in {
      Put("/items/", itemObj) ~> mainRoute ~> check {
        val item = responseAs[Item]
        item.name === "testItem"
        item.active === true
        item._id === itemObj._id
        Item.findAll().toList.size === 1
      }
    }
}

Where the PUT /items/ mapping corresponds to Spray HTTP Route: PUT / items /映射对应于Spray HTTP Route:

put {
      entity(as[Item]) { item ⇒
        complete {
          Item.saveOrUpdate(item)
          logger.info("putting item {}", item)

          HttpResponse(
            StatusCodes.OK,
            HttpEntity(ContentTypes.`application/json`, grater[Item].toCompactJSON(item))
          )
        }
      }
    }

And the saveOrUpdate definition is as follows: saveOrUpdate定义如下:

  def saveOrUpdate(t: T) = {
    t.id match {
      case Some(id) => dao.update(MongoDBObject("_id" -> id), t, false, false, new WriteConcern)
      case None => dao.insert(t)
    }

Now, the thing is the test fails on assertion 现在,问题是断言测试失败

item._id === itemObj._id

I've no idea why would _id change if I'm setting it up before doing the save or update of entity. 我不知道为什么在进行实体的保存或更新之前设置_id会发生变化。

Does anyone have any idea why does it acts that way and what can I do to fix this? 有谁知道它为什么会这样起作用,我该怎么解决?

Best, Marcin 最好,Marcin

我将JSON库从json4s更改为Spray Json,现在似乎可以使用了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM