Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If at all possible, don't define the document hierarchy this way -- you'll be fighting CouchDB every step of the way.</p> <p>You can't really do the hierarchy walk in a view. Views are meant for transferring each document independently on others (map) and generating some aggregate value from them (reduce).</p> <p>You could use lists to operate on multiple documents at the same time, but that's not a good solution either.</p> <p>If you need to keep this data structure (links to parent/child), I suggest you get assemble the structure from outside of CouchDB: get the parent document, get its children, get their children, etc.</p> <p>However, the preferred way of storing a tree in CouchDB is to have each node remember it's path in the tree:</p> <pre><code>{ "_id": "1", "name": "first", "something": "blue", "path": [1] } { "_id": "2", "name": "second", "something": "green", "path": [1,2] } { "_id": "3", "name": "second", "something": "red", "path": [1,2,3] } </code></pre> <p>You can then use this view to get a document's descendants:</p> <pre><code>function(doc) { for (var i in doc.path) { emit([doc.path[i], doc.path], doc) } } </code></pre> <p>To get descendants of <code>_id</code> 1 you can run this query:</p> <pre><code>http://c.com/db/_design/colors/_view/descendants?startkey=[1]&amp;endkey=[1,{}] </code></pre> <p>Storing a full path has its own drawbacks, too, though. I suggest you check this <a href="http://wiki.apache.org/couchdb/How_to_store_hierarchical_data" rel="noreferrer">CouchDB wiki page on trees</a>. The source for that is <a href="http://probablyprogramming.com/2008/07/04/storing-hierarchical-data-in-couchdb/" rel="noreferrer">this blog post by Paul Bonser</a>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload