title: Mongoose.js: How to Implement Tree Structure via Population
body: <p>I'm working on implementing a tree structure (similar to this one in the Mongo docs) using Mongoose 3.x, but I'm unsure of the best way to encapsulate all the logic for loading a specific node with its siblings and ancestors generally, and specifically how to best work with the population functionality where the ref is in the same collection as the ref-er.</p>
  
  <p>For some context, the tree I'm working with is one in which nodes are not edited but new children might be added at any time to any node.  So far I've got this working fine with a set of model methods that load objects after the initial find, but it seems there should be a better way to easily load a single branch with all the parent and sibling data I need with a single command in the controller, and encapsulate all the relevant population in some convenient find method on the model.</p>
  
  <p>The basic Schema I'm trying to work with, then, might be something like this (also available here: <a href="https://gist.github.com/3889616">https://gist.github.com/3889616</a>):</p>
  
  
  
  <pre class="lang-js prettyprint-override"><code>// Sub-document to store parent ref along with it's value (a form of caching)
  var Parent = new Schema({
      id: ObjectId
    , text: String
  });
  
  // Main tree-node element schema
  var Branch = new Schema({
      text: {
          type: String
        , required: true }
    , date: {type: Date, default: Date.now }
    , trail: [Parent]
    , parentBranchId: ObjectId
    , parentBranch: { type: Schema.Types.ObjectId, ref: 'Branch' }
    , _children: [{type: Schema.Types.ObjectId, ref: 'Branch'}]
    // These two have been commented out because I have no clue how to best implement 
    // , _priorSiblings: { type: Schema.Types.ObjectId, ref: 'Branch' }
    // , _followingSiblings: { type: Schema.Types.ObjectId, ref: 'Branch' }
  });
  </code></pre>
  
  <p>My hope would then be to be able to load a branch w/ the relevant related data via something like the following code, though at this point I'm pretty much lost and could be a good deal off base:</p>
  
  <pre class="lang-js prettyprint-override"><code>  req.app.models.Branch
      .findById(req.param("id"))
      .populate("parentBranch")
      .populate("parentBranch._children")
      .exec(...)
  </code></pre>
  
  <p>Ultimately, I'd love to have something I could abstract into a "tree" plugin for Mongoose, but I think I've got to get this architected correctly first. Any ideas?</p>
  
  <p>FWIW, at the end of the day, the data I really need for each branch is parent, next sibling, previous sibling (both in terms of creation time) and all children of parent.</p>
  
  <p>Thanks in advance!</p>