Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In the example you have above, to get all of the children for a document ID, your map function would look something like this:</p> <pre><code>function (doc) { if (doc.parent) { emit(doc.parent, { "_id": doc._id }); } } </code></pre> <p>(The "child" property you have in document 2 isn't even necessary.)</p> <p>Given your example data, this would emit twice:</p> <pre><code>[ "1", { "_id": "2" } ] [ "2", { "_id": "3" } ] </code></pre> <p>To get the child IDs for a single parent, you'd access the view like so:</p> <pre><code>http://.../db/_design/viewName/_view/childfunc?key="2" </code></pre> <p>To get the full document, add the include_docs parameter to the query string.</p> <p>If you want to get the parent and child at the same time, your map function is only a little different:</p> <pre><code>function (doc) { emit([ doc._id, "" ], { "_id": doc.id }); if (doc.parent) { emit([ doc.parent, doc._id ], { "_id": doc.id }) } } </code></pre> <p>This function can emit twice, so you end up with the following:</p> <pre><code>[ [ "1", "" ], { "_id": "1" } ] [ [ "1", "2" ], { "_id": "2" } ] [ [ "2", "" ], { "_id": "2" } ] [ [ "2", "3" ], { "_id": "3" } ] [ [ "3", "" ], { "_id": "3" } ] </code></pre> <p>Thanks to the sorting collation, the parents end up first (since their second key element is "") and the children end up after that. You don't have to use the child _id as the second key element, you could use whatever natural sorting property makes the most sense. (Creation date, name, title, whatever.)</p> <p>If you didn't have the "child" property, you could make a reduce function to get all of the parent's children:</p> <pre><code>function (key, vals) { var children = []; for (var docId in vals) { if (key[1] !== "") { children.push(docId); } } return children; } </code></pre> <p>That function looks to see if the child part of the key is not empty, and if so it pushes the document ID into an array. It loops over all of the values this way, and returns the array when done.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

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