我对couchDB还比较陌生,即使阅读了(最新存档现已删除)http://wiki.apache.org/couchdb/How_to_store_hierarchical_data(via 'Store the full path to each node as an attribute in that node's document'),仍然不太理解。
与其使用维基中描述的完整路径模式,我希望将子项作为UUID数组以及父项作为单个UUID进行跟踪。我倾向于这种方式,以便通过子项在子项数组中的位置来维护子项的顺序。
以下是couch中的一些示例文档,bucket可以包含bucket和item,item只能包含其他item。(UUID缩写以提高清晰度):
{_id: 3944
name: "top level bucket with two items"
type: "bucket",
parent: null
children: [8989, 4839]
}
{_id: 8989
name: "second level item with no sub items"
type: "item"
parent: 3944
}
{
_id: 4839
name: "second level bucket with one item"
type: "bucket",
parent: 3944
children: [5694]
}
{
_id: 5694
name: "third level item (has one sub item)"
type: "item",
parent: 4839,
children: [5390]
}
{
_id: 5390
name: "fourth level item"
type: "item"
parent: 5694
}
在map函数中,通过嵌入的文档ID查找文档是否可行?
function(doc) {
if(doc.type == "bucket" || doc.type == "item")
emit(doc, null); // still working on my key value output structure
if(doc.children) {
for(var i in doc.children) {
// can i look up a document here using ids from the children array?
doc.children[i]; // psuedo code
emit(); // the retrieved document would be emitted here
}
}
}
}
在理想的情况下,最终的JSON输出应该是这样的。
{"_id":3944,
"name":"top level bucket with two items",
"type":"bucket",
"parent":"",
"children":[
{"_id":8989, "name":"second level item with no sub items", "type":"item", "parent":3944},
{"_id": 4839, "name":"second level bucket with one item", "type":"bucket", "parent":3944, "children":[
{"_id":5694", "name":"third level item (has one sub item)", "type":"item", "parent": 4839, "children":[
{"_id":5390, "name":"fourth level item", "type":"item", "parent":5694}
]}
]}
]
}
include_docs
为 true),但内部的 emit 总是产生一个空对象作为值,并且排序似乎是任意的。 - James Hopkinchild._id
应该改为child.toString()
。这样修改后对我来说可以工作了。 - James Hopkin