CouchDB override a base JSON document

152 Views Asked by At

Is there a standard strategy (or agreed best-practice) in CouchDB for creating a JSON document that:

  • Is based on another document.
  • Contains a small number of JSON properties that represent overrides to the original document.

?

On receiving a request, CouchDB would calculate a result JSON document with the overrides applied and return it as a response. The user should not need to know or care that it's a composite document.

1

There are 1 best solutions below

3
On BEST ANSWER

Thats a very good Question because you asking for the possibility AND best-practice. The answer is - it depends ;-)

Generally you can do it with a CouchDB _list. Par example you get two docs from the _view the _list is based on, calculate the composite doc and respond it. The downside is that this server-side computing is very performance relevant. Don't use it when your composite doc will be requested in e.g. every user session. But when your use-case is smth like e.g. a request from another service once every night that should be ok.

CouchDB will love you when you take an alternative approach which leads in result to the situation that the composite doc is ready-to-respond stored in an index.

If you want to store the composite doc exactly as it should be a CouchDB _update handler can be used. You get the custom properties of the doc in the payload and the default doc from the database, merge everything into the composite doc and store that under an unique id (or overwrite the default doc).

Last but not least you can also use two approaches which are based on CouchDB _view. Both will not deliver the composite doc but the default doc and the custom overwrites in one request. First approach is to build a view with a multipart key which groups the parent doc (default data) and the child's (overwrites) together - second approach is to create a view with linked data: emit the custom settings as value of the view row and overwrite the view row _id with the _id of the default doc. When the view row gets requested with the query param ?include_docs=true default data and custom overwrites will be included in the result.