I want to update a JSON document in MongoDB like this:
{
"_id":{"$oid":"52dfc13ec20900c2093155cf"},
"email": "joe@domain.com",
"name": "joe",
"_version": 2
}
... and want to create a vermongo document like this on each update:
{
"_id { "_id":{"$oid":"52dfc13ec20900c2093155cf"}, "_version": 1},
"email": "joe@domain.com",
"name": "joe",
"_version": 1,
"_timestamp" : "2014-02-02T00:11:45.542"
}
I've tried a solution like this:
trait MyDao {
...
private val shadowCollection = ReactiveMongoPlugin.db.collection[JSONCollection](
collection.name + ".vermongo"
)
private def toVersioned(deleted: Boolean) = __.json.update(
(__ \ '_id).json.copyFrom((__ \ '_id \ '$oid).json.pickBranch) andThen
(__ \ '_id \ '_version).json.copyFrom((__ \ '_version).json.pick) andThen
// (__ \ '_version).json.put(if (deleted) JsString(s"deleted:$version") else JsNumber(version)) andThen
(__ \ '_timestamp).json.put(Json.toJson(LocalDateTime.now))
)
private def version(doc: JsValue, deleted: Boolean): Future[LastError] = {
shadowCollection.insert(doc.transform(toVersioned(deleted)).get)
}
}
The toVersioned
method has three problems:
Line 1: It doesn't create the multi-fields _id
Line 2: It crashes when I try to create _version
as the second field of _id
Line 3: (commented out) if parameter deleted
is true
, I'd like to mark the document as deleted by replacing "_version": 1
with "_version": "deleted:1"
; it is not clear to me how to handle the condition here.