开发者

Getting recursively nested document - Mongoose / Mongodb

开发者 https://www.devze.com 2023-04-02 03:25 出处:网络
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 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 do开发者_如何学Ccument 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...?


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消