基于当前用户属性发布流星集合

Publish Meteor Collection based on current user property

本文关键字:流星 集合 布流星 于当前 用户 属性      更新时间:2023-09-26

我正在尝试发布基于一个用户所属的敏感信息的集合

数据的例子:

Items:
  ItemA - GroupA
  ItemB - GroupA
  ItemC - GroupB
Users:
  UserA - GroupB
  UserB - GroupA
  UserC - GroupA

但是当我试着做

Meteor.publish('groupItems', function () {
  return Items.filter({ groupId : Meteor.user().profile.groupId });
}

失败,因为在这样的呼叫中我只允许访问Meteor.userId()。(在这个模糊的错误消息中表示,服务器端:

Exception from sub 5jnantRJ6gyHpTkTy Error: Meteor.userId can only be invoked in method calls. Use this.userId in publish functions.

问题:如何根据用户属性(如groupId)过滤Collection

在publish内部,如果用户登录了,您就可以访问它。userId,它允许您查询数据库以获取其余的用户信息。所以你可以将publish重写为:

Meteor.publish('groupItems', function () {
  if ( ! this.userId ) return [];  //return an empty array if no user is logged in.
  var user = Meteor.users.find( this.userId );
  return Items.filter({ groupId : user.profile.groupId });
});