1

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...?

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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).

1 Comment

thanks, i've added another bit explaining the problem a little more.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.