【问题标题】:Allow users to join public or private groups in Meteor?允许用户加入 Meteor 中的公共或私人群组?
【发布时间】:2018-05-17 16:17:13
【问题描述】:

我的 Meteor 应用程序中有用户可以加入的“组”。在组页面上,我显示了已加入的用户列表。我是这样发布的:

Meteor.publish("allUsers", function() {
  return Meteor.users.find({}, {fields: {name: 1, groups: 1}});
});

但是 id 也希望用户可以选择公开或私下加入群组。我能想到的唯一方法是为私人加入的组设置另一个字段,该字段仅发布给当前用户:

Meteor.publish('currentUser', function() {
  return Meteor.users.find(
    { _id: this.userId },
    { fields: { name: 1, groups: 1, groups-private: 1 } },
  );
});

这将允许我向当前用户显示他们私下加入的任何组,并显示公共组数据。

但是,这种方法有其局限性。我不能显示一个组的成员总数,任何私人成员都不能计算在内。我怎样才能绕过这个?我需要在组集合中存储号码吗?如果我这样做,我担心会获得比赛条件。

【问题讨论】:

  • groups 和 groups-private 的结构如何?它只是一组组名吗?也许您可以像您建议的那样拥有一个单独的集合,并在 allUsers 上运行一个观察者。如果新插入或更改或删除用户文档,则通过观察者相应地增加或减少计数。
  • 基本上是的,用户上的 groups 和 groups-private 字段是与组相关的 ID 数组。

标签: mongodb meteor


【解决方案1】:

在建模方面,用户和组之间存在多对多关系,但关系本身具有属性,即它可以是公共的或私有的。可以想象,您希望在未来跟踪该关系的其他属性,例如 joinedDate。

您可以存储一个包含额外属性的objects 数组,而不是在用户文档中存储groupId strings 数组。对于一位用户,这可能看起来像:

groups = [
  { groupId: 1, public: true },
  { groupId: 2, public: false },
  { groupId: 3 } // or just omit the public value altogether (default is private)
  ...
]

如果您想将组的所有public 成员发布给用户,您可以这样做:

Meteor.publish('publicUsersOfGroup',function(groupId){
  check(groupId,String);
  if (this.userId) {
    return Meteor.users.find({ groups: { $elemMatch: { groupId: groupId, public: true }});
  }
  this.ready();
});

如果你想计算一个组的成员,你可以这样做:

const publicCount = Meteor.users.find({ groups: { $elemMatch: { groupId: groupId, public: true }}).count();
const privateCount = Meteor.users.find({ groups: { $elemMatch: { groupId: groupId, public: {$ne: true }}).count();
const totalCount = Meteor.users.find({ groups: { $elemMatch: { groupId: groupId }).count();

为了提高性能,您需要索引这两个数组对象键。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-13
    • 1970-01-01
    • 2017-10-28
    • 1970-01-01
    相关资源
    最近更新 更多