【问题标题】:couchdb view to select records with key contained in array in documentcouchdb 视图以选择包含在文档数组中的键的记录
【发布时间】:2019-05-23 14:25:24
【问题描述】:

试图了解 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)
        }
    }
}

但事实并非如此。我知道...

我已经在其他视图上取得了成功(例如通过用户 ID 查找用户)并使用 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
});

非常感谢任何帮助。

【问题讨论】:

    标签: view couchdb couchdb-nano


    【解决方案1】:

    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]} 查询多个键

    btw 您可以发出 (doc.teams[curTeam], null) 并使用 {'key': 'team2', 'include_docs': true} 进行查询,这种方法将减少您的需要时查看。

    【讨论】:

    • 非常感谢......现在一切都变得更清楚了。
    • 好的!所以一分钱终于掉了......当我查询视图时..我没有尝试将值插入视图定义(如在 SQL 存储过程中)..我正在查询视图的输出!所以'key'会根据视图输出的第一列进行检查...... Doh!好的..现在我开始了!再次感谢..
    【解决方案2】:

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

    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”.. 我会很感激..

    【讨论】:

      猜你喜欢
      • 2022-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-18
      • 1970-01-01
      相关资源
      最近更新 更多