Search code examples
mongodbscalaspraysalat

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:

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.

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 {
      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:

  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.

Does anyone have any idea why does it acts that way and what can I do to fix this?

Best, Marcin


Solution

  • I changed the JSON library from json4s to Spray Json and it seems to work now.