Akshat Jiwan Sharma
Akshat Jiwan Sharma

Reputation: 16000

CouchDb : How to combine query and update requests into one?

The structure of my couchDb documents is like this

Posts

 {
      _id : '123132adsf',
    'userId' :'7236jsdfkaf',
     'Title' : 'This is a sample post'
}

User

{
   '_id' : '7236jsdfkaf',
   'count' : 1
}

The functionality that I am looking for is whenever the posts document is queried using the posts view the count field in the user that owns the post is updated.Is there any way to do this with a single couchDb request or will I have to make two requests to the database one for query and one for updation.

Upvotes: 1

Views: 248

Answers (2)

WiredPrairie
WiredPrairie

Reputation: 59763

Strictly speaking, when reading from a view, you'll need to add the functionality elsewhere.

In CouchDB, you'd need to be able to read the User document (and revision), and set that back during the read-only View operation.

Document get requests cannot affect (or even read) other documents during a read (views are read-only as well). Reads are intended to be cacheable for a given document version. Even the show (docs) and list functionality of CouchDB prevents this from happening.

Other notes:

Also, consider the issue of CouchDB not necessarily being the best option for doing auto-incrementing fields. Here's a good StackOverflow answer that details some of the challenges you might face. In essence, you may find that due to the way revisions of documents are managed in CouchDB, that frequent counter incrementing (such as you need), without frequent database compaction could lead to excessive disk utilization. Other systems may be better for doing page-view counting.

If you used the suggestion of using an Update function (docs), you've made caching pages/posts more expensive and require the CouchDB instance always return a revised document/post, every time the post is requested, which is very unnecessary (and should be cached on a web-tier if possible).

Upvotes: 2

Marcin Skórzewski
Marcin Skórzewski

Reputation: 2854

You could do it if you knew apriori the id of the post. You can use update function to change the value of the viewed field to 1 in the post document and return the data of the post. It is dirty hack, though. Instead the count in the user document you would use then the reduced sum of the viewed for the user. The thing is that, you have to know the id of the post before, because update function cannot do arbitrary query - it modifies the document it is given.

Upvotes: 2

Related Questions