title: Retrieving Hierarchical/Nested Data From CouchDB
body: <p>I'm pretty new to couchDB and even after reading <a href="https://web.archive.org/web/20111226184804/http://wiki.apache.org/couchdb/How_to_store_hierarchical_data" rel="nofollow noreferrer">(latest archive as now deleted) http://wiki.apache.org/couchdb/How_to_store_hierarchical_data  (via ‘Store the full path to each node as an attribute in that node's document’)</a> it's still not clicking just yet. </p>
  
  <p>Instead of using the full path pattern as described in the wiki I'm hoping to keep track of children as an array of UUIDs and the parent as a single UUID. I'm leaning towards this pattern so I can maintain the order of children by their positions in the children array.</p>
  
  <p>Here are some sample documents in couch, buckets can contain buckets and items, items can only contain other items. (UUIDs abbreviated for clarity):</p>
  
  <pre><code>{_id: 3944
   name: "top level bucket with two items"
   type: "bucket",
   parent: null
   children: [8989, 4839]
  }
  {_id: 8989
   name: "second level item with no sub items"
   type: "item"
   parent: 3944
  }
  {
   _id: 4839
   name: "second level bucket with one item"
   type: "bucket",
   parent: 3944
   children: [5694]
  }
  {
   _id: 5694
   name: "third level item (has one sub item)"
   type: "item",
   parent: 4839,
   children: [5390]
  }
  {
   _id: 5390
   name: "fourth level item"
   type: "item"
   parent: 5694
  }
  </code></pre>
  
  <p>Is it possible to look up a document by an embedded document id within a map function?</p>
  
  <pre><code>function(doc) {
      if(doc.type == "bucket" || doc.type == "item")
          emit(doc, null); // still working on my key value output structure
          if(doc.children) {
              for(var i in doc.children) {
                  // can i look up a document here using ids from the children array?
                  doc.children[i]; // psuedo code
                  emit(); // the retrieved document would be emitted here
              }
          }
       }
  }   
  </code></pre>
  
  <p>In an ideal world final JSON output would look something like.</p>
  
  <pre><code>{"_id":3944,
   "name":"top level bucket with two items",
   "type":"bucket",
   "parent":"",
   "children":[
       {"_id":8989, "name":"second level item with no sub items", "type":"item", "parent":3944},
       {"_id": 4839, "name":"second level bucket with one item", "type":"bucket", "parent":3944, "children":[
           {"_id":5694", "name":"third level item (has one sub item)", "type":"item", "parent": 4839, "children":[
               {"_id":5390, "name":"fourth level item", "type":"item", "parent":5694}
           ]}
       ]}
   ]
  }
  </code></pre>