CouchDB博客应用程序

use*_*028 4 couchdb

我已经阅读了"CouchDB - 权威指南"和网上发现的许多文章.我已经理解了Couch的工作原理,但仍有一些问题在我脑海中.

假设在一个简单的博客应用程序上工作:在帖子页面中,我想要显示帖子的数据和作者的数据.所以我想我必须将所有内容放在同一个文件中.好.如果我只需要在一个页面中显示作者的数据,我可以用视图来完成.好.

但如果作者更新了他的数据,我需要更新作者出现的每个文档?还是我错了?

我真的很想了解这种逻辑.

提前致谢.

Dom*_*nes 8

某些信息可以保留在同一文档中,在大多数情况下,这些信息都可以正常工作.

{
    "title": "Blog Article Title",
    "content": "... blah blah blah ...",
    "author": {
        "name": "someguy",
        "email": "someguy@foo.bar"
    },
    "type": "post"
}
Run Code Online (Sandbox Code Playgroud)

其他时候您可以使用_id另一个文档,以便在两个文档之间创建链接.

{
    "_id": "...",
    "title": "Blog Article Title",
    "content": "... blah blah blah ...",
    "author": "someguy",
    "type": "post"
}

{
    "_id": "someguy",
    "name": "Some Guy",
    "email": "someguy@foo.bar",
    "type": "author"
}
Run Code Online (Sandbox Code Playgroud)

乍一看,您需要2个单独的查询来检索这两个实体.但是,视图查询可以公开一个很好的小技巧.

function (doc) {
    if (doc.type === "post") {
        emit([doc.title, 0], null);                // output the main post
        emit([doc.title, 1], { _id: doc.author }); // output the author
    }
}
Run Code Online (Sandbox Code Playgroud)

您的视图将输出以下结果:(注意视图的排序方式)

{ ...
    "rows": [
        {
            "key": ["Blog Article Title", 0],
            "value": null
        },
        {
            "key": ["Blog Article Title", 1],
            "value": { "_id": "someguy" }
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

这不是那么有用,但是如果你添加include_docs=true到你的视图网址,你会得到这个结果:

{ ...
    "rows": [
        {
            "key": ["Blog Article Title", 0],
            "value": null,
            "doc": {
                "_id": "...",
                "title": "Blog Article Title",
                "content": "... blah blah blah ...",
                "author": "someguy",
                "type": "post"
            },
        },
        {
            "key": ["Blog Article Title", 1],
            "value": { "_id": "someguy" },
            "doc": {
                "_id": "someguy",
                "name": "Some Guy",
                "email": "someguy@foo.bar",
                "type": "author"
            }
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

现在两个实体都包含在1个查询中.:)

有关CouchDB中实体关系的更多信息,请查看此文章.