Reputation: 3
I am using CouchDb to store my documents and figuring out how to pull 1:1 related data on a document using CouchDb views.
For this given document structure,
{
_id: 'some_id',
doc_type: 'item',
name: 'Steel Caliper'
description: 'Steel Caliper description',
classification: {
_id: 'some_classification_id'
}
}
classification: {
_id: 'some_classification_id',
doc_type: 'classification',
name: 'Hand Tools'
}
When I retrieve a list of item documents using a CouchDb view like below (called with include_docs=true)
function(doc) {
if(doc_type==='item') {
emit(doc.name, null);
}
}
I get the item document but without the classification data pulled in.
{
"total_rows": 10,
"offset": 0,
"rows": [
{
"id": "some_id",
"key": "Steel Caliper",
"value": null,
"doc": {
"_id": "some_id",
"_rev": "1-65d32fe22a0b949ff73f23c65042ae3c"
"doc_type": "item"
"name": "Steel Caliper"
"classification": {
"_id": "some_classification_id"
}
}
},
{ ... }
}
Is there a way to pull in the classification data using a view and get an output like below ?
...
"doc": {
"_id": "some_id",
"_rev": "1-65d32fe22a0b949ff73f23c65042ae3c"
"doc_type": "item"
"name": "Steel Caliper"
"classification": {
"_id": "some_classification_id",
"doc_type": "classification",
"name": "Hand Tools"
}
}
...
Upvotes: 0
Views: 71
Reputation: 174
yes, this is called view collation. You can emit multiple docs if you are joining by _ids.
in your case you can call
function(doc) {
if(doc_type==='item') {
emit(doc.name, null);
if( doc.classification ){
emit( doc.classification._id, {_id: doc.classification._id });
}
}
}
you might still need play around with the returned result to get it into the form you want.
http://docs.couchdb.org/en/2.0.0/couchapp/views/joins.html
Upvotes: 1