Parse.com关系和ACL

时间:2014-12-02 17:12:11

标签: javascript parse-platform relationship

在博客上下文中考虑这个问题,我正在使用帖子和评论来代表我们的实际应用。

我们正在尝试使用Parse.com构建一个应用程序,并希望显示一个帖子列表,其中包含评论数量。似乎有两种方法可以做到这一点,其中一种似乎非常低效,但另一种方法要求所有用户都有对Post的写入权限。

低效的方式

在引用帖子的每个评论中存储关系,然后按照显示的帖子运行 1个查询来计算评论数量:

var postsWithComments = [
  // {post: post, commentCount: 0}
];

(new Parse.Query(Post))
.find()
.then(function (posts) {
  posts.forEach(function (post) {
    (new Parse.Query(Comment))
    .equalTo('post', post)
    .count()
    .then(function(commentCount) {
      postsWithComments.push({
        post: post,
        commentCount: commentCount
      });
    });
  });
});

不安全的方式

在Post上存储数组,指针或关系,引用属于它的每个Comment。这样可以快速轻松地进行计数,并通过Query.include()轻松访问。问题是每个用户都需要对Post 的写访问权才能添加评论。

是否存在另一种存储或查询我缺少的数据的方法?我需要的是一系列评论数量的帖子。用户可以点击以查看这些评论(此时我们可以加载实际数据)。

编辑添加:

手动维护的方式

进一步的Google搜索已经发现人们使用Cloud Code在子对象上使用afterSave更新父对象上的列来解决此问题。伪代码:

Parse.Cloud.afterSave("Comment", function(request, response) {
  var comment = request.object;

  var post = comment.get('post');

  var query = new Parse.Query(Parse.Object.extend('Comment'));
  query
    .equalTo('post', comment.get('post'))
    .count()
    .then(function(commentCount) {
      post
        .set('commentCount', commentCount)
        .save()
        .then(function() {
          response.success();
        }, function(error) {
          response.error(error);
        });
    });
});

0 个答案:

没有答案