App for the CouchDB App

I read “CouchDB - The Ultimate Guide” and many articles found on the Internet. I understood how Couch works, but some questions are still in my mind.

Suppose you are working on a simple blog application: On the posts page, I would like to show the post data and the author data. Therefore, I think I should put everything in the same document. OK. If I need to show only author data on one page, I can do this with a view. Good.

But if the author updates his data, do I need to update each document, where does the author appear? Or am I wrong?

I would really like to understand this logic.

Thanks in advance.

+4
source share
2 answers

Some information may be left in the same document, and in most cases this will work fine.

{ "title": "Blog Article Title", "content": "... blah blah blah ...", "author": { "name": "someguy", "email": " someguy@foo.bar " }, "type": "post" } 

In other cases, you can simply use the _id another document to create a link between two documents.

 { "_id": "...", "title": "Blog Article Title", "content": "... blah blah blah ...", "author": "someguy", "type": "post" } { "_id": "someguy", "name": "Some Guy", "email": " someguy@foo.bar ", "type": "author" } 

At first glance, you will need two separate queries to retrieve both objects. However, there is a nice little trick that query views can view.

 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" } } ] } 

This is not all that is useful as it is, but if you add include_docs=true to the URL of your view, you will get the following 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": " someguy@foo.bar ", "type": "author" } } ] } 

Now both objects are included in one request. :)

See this article for more information on entity relationships in CouchDB.

+8
source

Yes, you will need to update each document. The idea is to make big updates, such as rare ones, so although they are expensive calculations, you do not need to do many of them.

+3
source

Source: https://habr.com/ru/post/1345426/


All Articles