Model Users - Group relationship in CouchDB

I have group and user documents that I want to store in CouchDB, user can join multiple groups. One group can have thousands of users. Here are the documents I came up with:

Group: { "_id":"group1", "name":"abc", "type":"group" }
Group: { "_id":"group2", "name":"abc", "type":"group" }
User: { "_id":"user1", "login":"whatever", "groupIds": ["group1" , "group2"], "type":"user" }
User: { "_id":"user2", "login":"whatever", "groupIds": ["group2"], "type":"user" }

I want to get groups by user id. It seems like the best thing I can do is define this view:

function(doc) {
  if (doc.type == "user")
  {
    emit(doc._id, doc.groupIds);
  }
}

But in this case I need to get group ids in one request and then each group in separate request. Is there a way to write groups by user id view so that all groups were returned in one request to CouchDB?

Answers


You can use the linked documents syntax to get a list of group documents for a given user. Create this view:

function(doc) {
  if( doc.type === 'user' ) {
    var gids = doc.groupIds;
    for( var i=0, l=gids.length; i<l; i++) {
      emit( doc._id, { '_id': gids[i] } );
    }
  }
}

And then you will query this with the include_docs=true parameter, and Couch sees the special value of { "_id": "group1" } and retrieves that linked document for you. You will end up with all the group documents in the doc element of the returned hash row.


Need Your Help

Rails Tutorial 3.2 Chapter 8 error: NoMethodError in SessionsController#create

railstutorial.org nomethoderror

I'm going through the rails tutorial and my login page is throwing an exception after exercise 8.1.5 when I click the login button with no email or pw entered: