views:

96

answers:

1

I have a user document which has a group field. This field is an array of group ids. I would like to write a view that returns (groupid as key) -> (array of user docs as val). This mapping operation seems like a good beginning.

function(doc)
{
  var type = doc.type;
  var groups = doc.groups;
  if(type == "user" && groups.length > 0)
  {
    for(var i = 0; i < groups.length; i++)
    {
      emit(groups[i], doc);
    }
  }
}

But there's obviously something very wrong with my attempt at a reduce:

function(key, values, rereduce)
{
  var set = [];
  var seen = [];
  for(var i = 0; i < values.length; i++)
  {
    var _id = values[i]._id;
    if(seen.indexOf(_id) == -1)
    {
      seen.push(_id);
      set.push(values[i]);
    }
  }
  return set;
}

I'm running CouchDB 0.10dev. Any help appreciated.

A: 

The answer to this after checking on the CouchDB IRC is that you don't need reduce for this at all. Just provide a key=groupId, something like the following:

http://localhost:5984/somedb/_design/bygroup/_view/all?key=2

dnolen