计算 Meteor 帖子中的评论数量 [英] Count number comments in post in Meteor

查看:24
本文介绍了计算 Meteor 帖子中的评论数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想计算一个帖子的评论数,我必须在每次创建或删除新评论时保存评论数.

If I want to count the number of comments a post has got, I will have to save the number of comments every time a new comment is either created or removed.

确保每次创建或删除评论时,帖子都会根据评论数量进行更新的最有效和最安全的方法是什么?我试过 Curser.observe() 但它似乎有时会导致一些问题.我已经查看了我的代码,它应该没问题,但有时会发生一些不应该发生的更改,所以我担心当同时创建多个对象时,observe() 会导致一些问题.

What is the most efficient and secure way to ensure the posts are updated with the number of comments every time a comment is either created or removed? I have tried Curser.observe() but it seems it causes some problems sometimes. I have looked through my code and it should be OK but sometimes some changes happend when they shouldn't so I'm afraid that observe() causes some problems when multiple objects are created at the same time.

我看过meteor-collection-hooks,但他们不使用observe.我认为 observe 是最好的选择,因为它是原生的.其他人是如何解决这个问题的?

I have looked at meteor-collection-hooks and they don't use observe. I thought observe was the best choice since it is native. How does others solve this?

推荐答案

不要使用observe.它消耗资源并且不会超过一台服务器(在 N 个服务器正在观察变化时,您将有 N 个增量).我可以推荐两种可能的选择:

Don't use observe. It consumes resources and doesn't scale past one server (in N servers are observing the change, you will have N increments). I can recommend two possible options:

钩子

正如您所建议的,您可以使用 collection-hooks 来修改计数.具体来说,您可能想要使用 after.insertafter.remove 在您的 Comments 收藏中.Hooks 不需要额外的资源——它们只是修补底层集合代码来运行你的回调.

As you suggested, you can use collection-hooks to modify the count. Specifically you'd probably want to use after.insert and after.remove on your Comments collection. Hooks don't require extra resources - they just patch the underlying collection code to run your callback.

推荐阅读:了解 Meteor Collection Hooks

方法

如果您使用方法来插入和删除您的评论,您还可以修改您的评论同时计数.这样做的优点是不需要外部包,但它也需要在您的方法中混合一些关注点.

If you use methods to insert and remove your comments, you can also modify your comment counts at the same time. This has the advantage of not requiring an external package, however it also requires some mixing of concerns in your methods.

这篇关于计算 Meteor 帖子中的评论数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆