我很难理解 CouchDB 的 linked documents特征。
我有两个 types
存储在单个 CouchDB 数据库中的数据:
{
"id":"1",
"type": "track",
"title": "Bohemian Rhapsody"
}
{
"id":"2",
"type": "artist",
"name": "Queen",
"tracks": ["1"]
}
我的印象是我可以编写如下所示的 View 并发出以下文档:
{
"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
这不是我希望的返回 - 你有什么建议吗?谢谢
最佳答案
好的,我终于明白你要做什么了。是的,这是可能的。这是怎么做的。
你有 2 个文件
{
"_id":"anyvalue",
"type": "track",
"title": "Bohemian Rhapsody"
}
{
"_id":"2",
"type": "artist",
"name": "Queen",
"tracks": ["anyvalue"]
}
你做错的是没有在轨道的值(数组中的项目)周围加上引号。
2) 引用 id 必须是 _id 才能工作。区别值得注意,因为您可以有 id 字段,但只有 _id 用于标识文档。
对于您想要的结果,此 View 就足够了
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 参数查询 couch db View 。这是您在 iris couch 上创建的数据库的最终结果。
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"
}
}
]
}
杰森在这篇文章中很好地解释了它
Best way to do one-to-many "JOIN" in CouchDB
此链接也有助于沙发数据库中的实体关系
http://wiki.apache.org/couchdb/EntityRelationship
关于 View 中的 CouchDB 链接文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14601845/