4

我很难理解 CouchDB 的链接文档功能。

我有两个types数据存储在一个 CouchDB 数据库中:

{
  "id":"1",
  "type": "track",
  "title": "Bohemian Rhapsody"
}

{
  "id":"2",
  "type": "artist",
  "name": "Queen",
  "tracks": ["1"]
}

我的印象是我可以编写如下视图并发出以下文档:

{
  "id":"2",
  "type": "artist",
  "name": "Queen",
  "tracks": [
    {
      "id":"1",
      "type": "track",
      "title": "Bohemian Rhapsody"
    }
  ]
}

我一直在尝试这种观点,但它没有按我预期的方式工作:

function(doc) {
  if(doc.type == 'artist') {
    var tracks = [];
    for(var i = 0; i < doc.tracks.length; i++) {
      tracks.push({_id:doc.tracks[i]});
    }

    newdoc = eval(uneval(doc));
    newdoc.tracks = tracks;

    emit(doc._id,newdoc);
  }
}

这里的例子:http: //jphastings.iriscouch.com/_utils/database.html ?music/_design/test/_view/linked

这不是我希望的回报 - 你有什么建议吗?谢谢

4

1 回答 1

4

好的,我终于明白你要做什么了。是的,这是可能的。这就是方法。

您有 2 个文件

{
"_id":"anyvalue",
"type": "track",
"title": "Bohemian Rhapsody"
}

{
"_id":"2",
"type": "artist",
"name": "Queen",
"tracks": ["anyvalue"]
}

您做错的事情是没有在轨道值(数组中的项目)周围加上引号。

2)参考 id 必须是 _id 才能工作。差异值得注意,因为您可以有 id 字段但只有 _id 用于识别文档。

对于您想要的结果,此视图就足够了

function(doc) {
    if (doc.type === 'artist') {
        for (var i in doc.tracks) {
            var id = doc.tracks[i];
            emit(id, { _id: id });
        }
    }
}

你想要做的是在 for 循环中使用一个发出函数来发出每个艺术家的“轨道”的 id 字段。

然后您想使用 include_docs=true 参数查询沙发数据库视图。这是您在 iris 沙发上创建的数据库的最终结果。

http://jphastings.iriscouch.com/music/_design/test/_view/nested?reduce=false&include_docs=true

 {
"total_rows": 3,
"offset": 0,
"rows": [
 {
  "id": "0b86008d8490abf0b7e4f15f0c6a50a7",
  "key": "0b86008d8490abf0b7e4f15f0c6a463b",
  "value": {
    "_id": "0b86008d8490abf0b7e4f15f0c6a463b"
  },
  "doc": {
    "_id": "0b86008d8490abf0b7e4f15f0c6a463b",
    "_rev": "3-7e4ba3bfedd29a07898125c09dd7262e",
    "type": "track",
    "title": "Boheniam Rhapsody"
  }
},
{
  "id": "0b86008d8490abf0b7e4f15f0c6a50a7",
  "key": "0b86008d8490abf0b7e4f15f0c6a5ae2",
  "value": {
    "_id": "0b86008d8490abf0b7e4f15f0c6a5ae2"
  },
  "doc": {
    "_id": "0b86008d8490abf0b7e4f15f0c6a5ae2",
    "_rev": "2-b3989dd37ef4d8ed58516835900b549e",
    "type": "track",
    "title": "Another one bites the dust"
  }
},
{
  "id": "0b86008d8490abf0b7e4f15f0c6a695e",
  "key": "0b86008d8490abf0b7e4f15f0c6a6353",
  "value": {
    "_id": "0b86008d8490abf0b7e4f15f0c6a6353"
  },
  "doc": {
    "_id": "0b86008d8490abf0b7e4f15f0c6a6353",
    "_rev": "2-0383f18c198b813943615d2bf59c212a",
    "type": "track",
    "title": "Stripper Vicar"
  }
 }
]
}

杰森在这篇文章中很好地解释了它

在 CouchDB 中进行一对多“JOIN”的最佳方式

这个链接也有助于沙发数据库中的实体关系

http://wiki.apache.org/couchdb/EntityRelationship

于 2013-01-30T11:37:15.583 回答