Build a JSON tree from materialized paths Build a JSON tree from materialized paths json json

Build a JSON tree from materialized paths


var Comment = new Schema({    date      : {        type        : Date,        default     : Date.now    },    event: ObjectId,    body      : String,    pathComment  : String,    user: Array})Comment.virtual('level').get(function() {    return this.pathComment.split(',').length;});Comment.find({event: event.id}).sort({pathComment:1}).exec(function(err, comment){            var collectComment = function(comment){                return  {                    body: comment.body,                    event: comment.event,                    pathComment: comment.pathComment,                    id: comment._id,                    level: comment.level,                    user: comment.user[0],                    date: comment.date,                    comments: []                };            }            var tplComment = [];            var createChildComment = function(comment, currentNode, level){                if(level==1){                    comment.push(collectComment(currentNode));                }else{                    createChildComment(comment[comment.length-1]['comments'], currentNode,level-1);                }                return;            }            for(var k in comment){               createChildComment(tplComment, comment[k],comment[k].level);            }});