开发者

Passing an argument to map.js in a CouchApp view

开发者 https://www.devze.com 2023-03-22 02:52 出处:网络
I have a CouchApp that functions like a social network. I have a like button which, when clicked by a user, creates and saves a CouchDB JSON document with the fields post_id (the ID of the post that w

I have a CouchApp that functions like a social network. I have a like button which, when clicked by a user, creates and saves a CouchDB JSON document with the fields post_id (the ID of the post that was liked), user_id (the ID of the user who liked the post), and type (value is "开发者_高级运维like," to indicate that the document is a like).

Alongside the post, I'd like to indicate the number of likes it has received. My map function looks like this:

function(doc) {
  if (doc.type && doc.type == 'like') {
    emit(doc.post_id, 1);
  }
}

and my reduce, this:

function(post_ids, likes) {
  return sum(likes);
}

My problem is, this function returns the sum of ALL the likes in ALL posts in the site. I'm thinking that my reduce.js is fine and that maybe I could tweak my map.js to accept a post_id argument so I can retrieve only the likes from that post_id, but how do I do that? The post_id comes from the design document, of course, when the "Like" button is clicked.

Thanks.


You need to look into the group view parameter. If you supply no querystring parameters, the default is to reduce the entire contents of the view. Once you apply group=true, you can also use key or startkey/endkey to pick out the post id(s) you need.

Also, there are built-in reduce functions that can perform basic reduce operations much more efficiently. (since they are compiled erlang code, not javascript source) Just put _count in place of your entire reduce.js. (You can even leave off the 1 in your emit)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号