How does mongoose document tree get the whole document tree through query?

  node.js, question
  1. Question: How does mongoose document tree query and generate json objects

  2. schema:

    var ImoocSchema = new mongoose.Schema({
     id:Number,
     name:String,
     url:String,
     parent:String
     })

    When I deposited it, parent looked at it according to’ course’ and id, so I checked it from top to bottom. There is also the feeling that such nesting is problematic and looks too ugly.

  3. Generate JSON

    exports.getLessondata = function(req,res){

    //When designing the database, the fields will be designed directly, and when querying the tree structure data in the later period, the whole structure will be returned directly.
     var _id = req.body._id;
     //Data returned to request
     var data = {};
     Imooc.findById(_id,function(err,lesson){
     if(err){console.log(err);  bracket
     Var lessonId = 'course' plus lesson.id;
     data.lessonName = lesson.name;
     data.chapters = []
     //Write chapter data to the requested data that needs to be returned.
     Imooc.find({parent:lessonId},function(err,docs){
     for(var i = 0;     i < docs.length;  I plus)
     var chapterName = docs[i].name
     data.chapters[i] = {};
     data.chapters[i].sections = [];
     data.chapters[i].name = chapterName;
     
     Imooc.find({parent:chapterName},function(err,docss){
     if(err){console.log(err);  bracket
     // console.log(data.chapters[i].sections)
     for(var j = 0;     j < docss.length;  J plus)
     var name = docss[j].name
     var url = docss[j].url
     var section = {name:name,url:url}
     //When I did it myself, this place reported an error: undefined.
     data.chapters[i].sections.push(section)
     bracket
     })
     bracket
     })
     })

    bracket

  4. New slag code

For generating javascript objectslean(), take a look at the document about lean ()