Vida
Vida

Reputation: 540

couchdb view to select records with key contained in array in document

Trying to get my head around couchdb... first time using a database that isn't SQL.

Trying to figure out how to write a view that returns all users in a particular team....

User docs are like this:

{
   "_id": "e3031a9eb16dd879fbe78b61f800378b",
   "_rev": "3-8aaf2d203b92b684fbd7a27a7dff9108",
   "type": "user",
   "userid": "myuserid",
   "password": "mypassword",
   "email": "[email protected]",    
   "firstname": "joe",
   "lastname": "smith",
   "org": "companyname",
   "teams": [
       "team2",
       "otherTeam"
       ]
}

You can see the teams array there...

I've been trying stuff like:

function(doc) {
    if (doc.type == 'user') {
        if ((doc.teams.indexOf(searchString) > -1){
            emit(doc.user, doc)
        }
    }
}

But thats not it. I know...

I've had success with other views (like find a user by userid) and calling them with nano like:

db.view('users', 'by_userid', {'key': userid, 'include_docs': true},     
  function(err, body) {
    .. etc
});

But I'm pretty confused as to how to do this one...

db.view('users', 'by_team', {'key': teamName, 'include_docs': true},     
  function(err, body) {
    .. etc
});

Any help greatly appreciated.

Upvotes: 2

Views: 3334

Answers (2)

the4lt
the4lt

Reputation: 121

CouchDb map function creates a view = simple dictionary of key-value pairs. Builtin emit function takes 2 parameters, the first one will be a key in the view, and second one will be a value. So after your map, view 'by_team' should looks like

team2 : {document where team2 is in the teams arr},
team2 : {other document where team2 is in the teams arr},
team2 : {and other document where team2 is in the teams arr},
otherTeam : {document where otherTeam is in the teams arr},
otherTeam : {etc}

And when you query with {'key': 'team2'} db.view just select values with specified key. You also can use {keys : [array, of, keys]} for querying multiply keys

btw you can emit (doc.teams[curTeam], null) and query with {'key': 'team2', 'include_docs': true} this approach will reduce the size of your view if needed.

Upvotes: 3

Vida
Vida

Reputation: 540

Just FYI, found the answer via this post:

CouchDb view - key in a list

My code looks like this for the view:

function(doc) {
   if(doc.teams) {
      for (var curTeam in doc.teams) {
        emit (doc.teams[curTeam],doc);
      }
  }
}

And then called like this:

db.view('users', 'by_team', {'key': 'team2'},function(err, body) {
  if (!err) {
    body.rows.forEach(function(doc) {
      console.log(doc);
    });
  }
});

I still don't fully understand it.. but it works... heh... If anyone can explain how 'team2' gets used in the view.. I'd appreciate it..

Upvotes: 0

Related Questions