【发布时间】:2011-03-03 06:49:27
【问题描述】:
我正在寻找相当于“SQL 连接”的 CouchDB。
在我的示例中,CouchDB 文档是列表元素:
{ "type" : "el", "id" : "1", "content" : "first" }
{ "type" : "el", "id" : "2", "content" : "second" }
{ "type" : "el", "id" : "3", "content" : "third" }
有一个文档定义了列表:
{ "type" : "list", "elements" : ["2","1"] , "id" : "abc123" }
如您所见,第三个元素已被删除,它不再是列表的一部分。所以它不能是结果的一部分。现在我想要一个返回内容元素的视图,包括正确的顺序。
结果可能是:
{ "content" : ["second", "first"] }
在这种情况下,元素的顺序已经是应该的了。另一个可能的结果:
{ "content" : [{"content" : "first", "order" : 2},{"content" : "second", "order" : 1}] }
我开始写地图功能:
map = function (doc) {
if (doc.type === 'el') {
emit(doc.id, {"content" : doc.content}); //emit the id and the content
exit;
}
if (doc.type === 'list') {
for ( var i=0, l=doc.elements.length; i<l; ++i ){
emit(doc.elements[i], { "order" : i }); //emit the id and the order
}
}
}
这是我所能得到的。你能纠正我的错误并写一个reduce函数吗?请记住,第三个文档不能是结果的一部分。
当然你也可以写一个不同的地图函数。但是文档的结构(一个定义元素文档和每个条目的一个条目文档)不能更改。
编辑:不要错过 JasonSmith 对他的回答的评论,他在其中描述了如何更短地做到这一点。
【问题讨论】: