I have read the "CouchDB - The definitive guide" and many articles found on the web. I have understood how Couch works but some questions are still in my mind.
Suppose to work on a simple blog application: In the post page I'd want to show post's data and author's data. So I think I have to put everything in the same document. Ok. If I need to show only the author's data in a single page I can do it with a view. Ok.
But If the author update his data, I need to update each document where the author appear? Or am I wrong?
I'd really love to understand this logic.
Thanks in advance.
Some information can be left in the same document, and in most cases that will work just fine.
{
"title": "Blog Article Title",
"content": "... blah blah blah ...",
"author": {
"name": "someguy",
"email": "[email protected]"
},
"type": "post"
}
Other times you can just use the _id
of another document in order to create a link between the 2 documents.
{
"_id": "...",
"title": "Blog Article Title",
"content": "... blah blah blah ...",
"author": "someguy",
"type": "post"
}
{
"_id": "someguy",
"name": "Some Guy",
"email": "[email protected]",
"type": "author"
}
At first glance, you'll need 2 separate queries to retrieve both entities. However, there is a nice little trick that view queries can expose.
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
}
}
Your view will output this result: (note how the view is sorted)
{ ...
"rows": [
{
"key": ["Blog Article Title", 0],
"value": null
},
{
"key": ["Blog Article Title", 1],
"value": { "_id": "someguy" }
}
]
}
That's not all that useful as it is, but if you add include_docs=true
to your view URL, you'll get this result:
{ ...
"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": "[email protected]",
"type": "author"
}
}
]
}
Now both entities are included in 1 query. :)
Check out this article for more information about entity relationships in CouchDB.
Yes you would need to update every document. The idea is big updates like that are rare, so even though they are computationally expensive you shouldn't have to do many of them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With