在 CouchApp 视图中将参数传递给 map.js
我有一个 CouchApp,其功能类似于社交网络。我有一个“赞”按钮,当用户单击该按钮时,会创建并保存一个 CouchDB JSON 文档,其中包含字段 post_id(喜欢的帖子的 ID)、user_id(喜欢该帖子的用户的 ID),然后输入(值为“like”,表示该文档是相似的)。
除了这篇文章之外,我还想指出它收到的点赞数。我的地图函数如下所示:
function(doc) {
if (doc.type && doc.type == 'like') {
emit(doc.post_id, 1);
}
}
我的缩减函数如下:
function(post_ids, likes) {
return sum(likes);
}
我的问题是,该函数返回网站中所有帖子中所有点赞的总和。我认为我的reduce.js 很好,也许我可以调整我的map.js 以接受post_id 参数,这样我就可以只从该post_id 中检索喜欢的内容,但我该怎么做呢? post_id当然来自设计文档,当点击“Like”按钮时。
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要查看
group
视图参数。如果您不提供查询字符串参数,则默认情况下会减少视图的全部内容。应用group=true
后,您还可以使用key
或startkey/endkey
来选择您需要的帖子ID。此外,还有内置reduce函数可以更有效地执行基本的reduce操作。 (因为它们是编译的 erlang 代码,而不是 javascript 源代码)只需将
_count
代替整个reduce.js
即可。 (您甚至可以在emit
中省略1
)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 applygroup=true
, you can also usekey
orstartkey/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 entirereduce.js
. (You can even leave off the1
in youremit
)