基于数据库中信息选择性发布在流星中的正确方法是什么?



例如,当您的权限基于组时,并且用户文档具有用户属于的组的列表。我将在项目集合中发布文档,您应该只能使用匹配您属于的组的groupOwner字段查看项目。

如果您可以在发布中自动自动运行,那就太好了,但我怀疑您可以:

Meteor.publish 'screened-items', ->
  Deps.autorun ->
    user = Users.findOne @userId
    return Items.find {groupOwner: {$in: user.groups}}

如果您不能,这是我能想到的最好的,但是它将很慢且记忆力密集。这是唯一的方法吗?

Meteor.publish 'screened-items', ->
  user = Users.findOne @userId
  # (hope that the db doesn't change between this line and the observeChanges)
  saved_items = Items.find({groupOwner: {$in: user.groups}}).fetch()
  # call @added on each item
  handle = Users.findOne(@userId).observeChanges {
    changed: (_, fields) =>
      if fields.groups
        new_items = Items.find({groupOwner: {$in: fields.groups}}).fetch()
        # compare new_items to saved_items, and call @added() or @removed() for each difference
  }
  @ready()
  @.onStop ->
    handle.stop()

您可以实现这两种方法:

  1. 使用publish-with-relations软件包,例如:

    Meteor.publish 'screend-items', ->
      # select the current user
      Meteor.publishWithRelations
        handle: this
        collection: Meteor.users
        filter:
          _id: @userId
        options:
          fields:
            groups: 1
        mappings: [
          key: 'groupOwner'  # and map to the `groupOwner` field on Items
          collection: Items
        ]
    
  2. 不符合关系,提供了用于出版的简洁列表

    Items._ensureIndex(userIds: 1) # best to index this field
    # basic publications
    Meteor.publish 'screend-items', ->
      # don't expose `userIds` to the client
      return Items.find({userIds: @userId}, {fields: userIds: false})
    

如果您希望发布的文档在用户ID更改时更改,那是默认行为。

但是,如果已登录的用户更改,则使用新值重新运行。 - 来自docs.meteor.com。

deps.autorun()仅在客户端上工作,而seeor.publish()仅在服务器上工作。因此,您无法在发布中自动自动。

如果您可以让客户端查看它们所在的"组",则代码更简单,因为当组更改时,您可以启动并停止订阅。这样:

//on client 
Deps.autorun( function() {
  Meteor.subscribe( 'items', Meteor.user().groups );
});
//on server
Meteor.publish( 'items', function( groups ){
  var self = this;
  var user = Meteor.users.findOne( {_id: self.userId});
  if ( ! (user && user.groups === groups) )
    return;
  return Items.find({groupOwner: {$in: groups}});
});

否则,您需要在发布功能中使用两个观察者 - 一个观察用户的更改组,另一个用于管理组中的发布项目。请参阅以这种方式进行收藏的示例。

相关内容

最新更新