Igl3
Igl3

Reputation: 5108

Couchbase view custom reduce

i'm not sure if the title of the questions fits, if you know a better one, let me know ;) I just named it like this, because i'm thinking if i could solve my problem with a custom reduce function.

I have two types of objects:

Vehicles:

{
  "id": "1G1JC5444R7252367",
  "type": "Vehicle"
}

Users:

{
  "company": "companyname",
  "type": "User",
  "parts": [
    {
      "company": "companyname",
      "id": "1G1JC5444R7252367",
      "active": true
    },
    {
      "company": "companyname",
      "id": "1G1135644R7252367",
      "active": false
    }
  ]
}

What i want is a View which returns me all vehicles of a certain company. But the company is only stored in the User object.

This is how far I got in the mapfunction:

function (doc, meta) {
  if(doc.type == 'User'){
    if(doc.parts){

      Array.prototype.contains = function ( needle ) {
        for (var i in this) {
          if (this[i] == needle) return true;
        }
        return false;
      };

      var ids = new Array(doc.parts.length);

      for(var k in doc.parts){
        if(doc.parts[k].active) {
          if(!vins.contains(doc.parts[k].id)) {
            if (doc.parts[k].company && doc.parts[k].id ) {
              ids.push(doc.parts[k].id);
              emit(doc.parts[k].company, doc.parts[k].id);
            }
          }
        }
      }
    }
  }
}

But this only returns me the company as key and the id of the vehicle as value. So i get a User document. Can I somehow loop through the documents again in the map function and get all vehicles according to the ids in my ids array?

Saving the company in the vehicle itself also is not desired, because the company is not the vehicles company itself but the company of the parts.

Thanks for any help in forward.

Upvotes: 1

Views: 93

Answers (1)

adonoho
adonoho

Reputation: 4339

A Couchbase view can only operate on the document presented to it. As you discovered, it can only partially do what you want.

The real problem isn't the view though but is your data model. You appear to have designed your data model as if you were using a relational database. The calculation you are attempting is a kind of join.

A fundamental concept with document databases is that a document should represent all of the information pertinent to some kind of event. This concept is what allows document databases to horizontally scale. You should not worry about data duplication. Locality of access is the key to an appropriate map-reduce data model.

I would redesign your data model.

Upvotes: 1

Related Questions