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

View couchdb视图选择文档数组中包含键的记录,view,couchdb,couchdb-nano,View,Couchdb,Couchdb Nano,试着让我的头脑在couchdb周围。。。第一次使用的数据库不是SQL 试图找出如何编写返回特定团队中所有用户的视图 用户文档如下所示: { "_id": "e3031a9eb16dd879fbe78b61f800378b", "_rev": "3-8aaf2d203b92b684fbd7a27a7dff9108", "type": "user", "userid": "myuserid", "password": "mypassword", "email":

试着让我的头脑在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"
       ]
}
db.view('users', 'by_team', {'key': 'team2'},function(err, body) {
  if (!err) {
    body.rows.forEach(function(doc) {
      console.log(doc);
    });
  }
});
你可以在那里看到团队阵列

我一直在尝试这样的东西:

function(doc) {
    if (doc.type == 'user') {
        if ((doc.teams.indexOf(searchString) > -1){
            emit(doc.user, doc)
        }
    }
}
但事实并非如此。我知道

我成功地使用了其他视图(如通过userid查找用户),并使用nano-like调用它们:

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
});

非常感谢您的帮助。

仅供参考,请通过以下帖子找到答案:

对于视图,我的代码如下所示:

function(doc) {
   if(doc.teams) {
      for (var curTeam in doc.teams) {
        emit (doc.teams[curTeam],doc);
      }
  }
}
然后这样叫:

{
   "_id": "e3031a9eb16dd879fbe78b61f800378b",
   "_rev": "3-8aaf2d203b92b684fbd7a27a7dff9108",
   "type": "user",
   "userid": "myuserid",
   "password": "mypassword",
   "email": "myemail@myjob.com",    
   "firstname": "joe",
   "lastname": "smith",
   "org": "companyname",
   "teams": [
       "team2",
       "otherTeam"
       ]
}
db.view('users', 'by_team', {'key': 'team2'},function(err, body) {
  if (!err) {
    body.rows.forEach(function(doc) {
      console.log(doc);
    });
  }
});
我还是不完全明白。。但它是有效的。。。嘿。。。
如果有人能解释“团队2”是如何在视图中使用的。。非常感谢..

CouchDb映射函数创建一个视图=键值对的简单字典。内置的emit函数有两个参数,第一个是视图中的键,第二个是值。因此,在您的地图之后,视图“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]}查询多个键


顺便说一句,您可以使用{'key':'team2','include_docs':true}发出(doc.teams[curTeam],null)和查询。如果需要,这种方法将减少视图的大小。

非常感谢。。现在一切都变得更清楚了。好吧!所以硬币终于掉了。。。当我查询视图时。。我没有尝试将值插入视图定义(如在SQL存储过程中)。。我正在查询视图的输出!!因此,根据视图输出的第一列检查“key”。。。啊!可以现在我明白了!再次感谢。。