Question

I have a recursively nested schema just like comments work on a blog. What is the best way to pull an individually nested document out which may be several layers deep.

I understand that you get the root document out, then drill down to the document you want, but in a recursive situation where the wanted document may be an unknown number of levels deep how should I retrive it. Loop through and do an if to see if its the correct one...?

Was it helpful?

Solution

looks like there is no mongoose way to do it so im using a recursive find function like this for finding a folder which is nested:

var findFolder = function(searchFolder ,folder_id, cb){
  var folder = searchFolder.folders.id(folder_id);
  if(folder == undefined){
    _.each(searchFolder.folders, function(subFolder){
      findFolder(subFolder, folder_id, cb);
    }.bind(this))
  }else{
    cb(folder);//when found callback passing the doc
  };
};

p.s. this uses the underscore library

OTHER TIPS

Quick answer is: you can't load sub document, because mongodb does not support it. In mongodb you can load only root document and then extract from it sub document at client side (from any level of deep).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top