Build a JSON tree from materialized paths

后端 未结 1 1290
一整个雨季
一整个雨季 2021-02-08 02:29

I\'m planning on using materialized paths in MongoDB to represent a tree and need to convert the materialized paths back into a JSON tree.

ex. // Materialized path

相关标签:
1条回答
  • 2021-02-08 03:06
    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);
                }
    });
    
    0 讨论(0)
提交回复
热议问题