couchdb视图用于选择包含在文档中的数组中的键的记录

时间:2015-12-17 17:05:39

标签: view couchdb couchdb-nano

试图绕过couchdb ...第一次使用不是SQL的数据库。

试图弄清楚如何编写一个返回特定团队中所有用户的视图....

用户文档是这样的:

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

你可以在那里看到球队阵列......

我一直在尝试这样的事情:

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

但那不是它。我知道......

我已经成功使用其他观点(比如通过userid查找用户)并使用nano调用它们:

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

但我对如何做到这一点感到很困惑......

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

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

CouchDb map函数创建一个view =简单的键值对字典。内置 emit 函数有2个参数,第一个是视图中的键,第二个是值。因此,在您的地图之后,请查看' by_team'应该看起来像

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}

当您使用{' key':' team2'} db.view进行查询时,只需选择具有指定键的值即可。您还可以使用{keys:[array,of,keys]}来查询乘法键

btw 你可以发出(doc.teams [curTeam],null)并使用{' key':' team2',' include_docs':true}如果需要,这种方法会减少视图的大小。

答案 1 :(得分:0)

仅供参考,通过这篇文章找到答案:

CouchDb view - key in a list

我的代码对于视图来说是这样的:

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

然后这样叫:

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

我仍然不能完全理解它......但它有效......嘿...... 如果有人可以解释' team2'在视图中使用..我很欣赏它..

相关问题