Given a mongodb collection that stores trees as nodes with parent references this methods returns a deep nested tree where every child nodes are stored in a property childs[Seq]
def getTree(rootId: BSONObjectID): Future[CategoryTreeNode] = {
def collect(parent: CategoryTreeNode): Future[CategoryTreeNode] = {
// Query the database - returns a Future[Seq[CategoryTreeNode]]
getChilds(parent._id.get).map {
// Seq[CategoryTreeNode]
childs =>
Future.sequence(
childs.map(child => collect(child)) // Recursion
).map(childSeq => parent.copy(childs = Some(childSeq)))
}.flatMap(x => x).map(y => y)
}
// Find the root node and start the recursion
findOne[CategoryTreeNode](Json.obj("_id" -> rootId)).map(maybeNode => maybeNode match {
case None => throw new RuntimeException("Current node not found by id!")
case Some(node) => collect(node)
}).flatMap(x => x)
}