Skip to content

Instantly share code, notes, and snippets.

@jkyamog
Last active December 17, 2015 23:09
Show Gist options
  • Save jkyamog/5687702 to your computer and use it in GitHub Desktop.
Save jkyamog/5687702 to your computer and use it in GitHub Desktop.
reactive mongo that can be used with angular resources. make sure to perform validation before inserts and updates. there are 2 json readers, this is used to transform mongo object to and from the front end (FE). Then 2 sample api calls to use them, there is an assumption that id or _id will always be there, otherwise its a runtime exception.
val mongoToFE =
__.json.update((__ \ 'id).json.copyFrom( (__ \ '_id \ '$oid).json.pick )) andThen
(__ \ '_id).json.prune
val FEtoMongo =
__.json.update((__ \ '_id \ '$oid).json.copyFrom( (__ \ 'id).json.pick )) andThen
(__ \ 'id).json.prune
Async {
val items = collection.find(BSONDocument("_id" -> objectId)).cursor[JsObject]
items.headOption.map {
case None => NotFound
case item => Ok(item.get.transform(mongoToFE).get)
}
}
Async {
collection.update(BSONDocument("_id" -> objectId), json.transform(FEtoMongo).get).map { _ =>
NoContent
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment