3

我今天才开始使用流星,似乎无法弄清楚我做错了什么。我有一个在发布函数内部运行的查询,但是这个查询被另一个查询的结果过滤了。

简而言之,当我将文档添加到正在发布的数据库(CollectionTwo)时,它会按预期工作,但是当我在用于过滤的数据库(CollectionOne)中进行更改时,meteor 不会做出反应.

CollectionOne = new Meteor.Collection("one")
CollectionTwo = new Meteor.Collection("two")

Meteor.publish("items", ->
  not_hidden = CollectionOne.find().fetch()
  return CollectionTwo.find( _id: {'$in':( t.my_id for t in not_hidden )} )
)

同时,在客户端...

CollectionOne = new Meteor.Collection("one")
CollectionTwo = new Meteor.Collection("two")

Meteor.subscribe("items")

_.extend( Template.items,
  items: ->
    not_hidden = CollectionOne.find().fetch()
    return CollectionTwo.find( _id: {'$in':( t.my_id for t in not_hidden )} )
)

任何想法可能是适当的解决方案?

4

3 回答 3

6

Meteor.publish反应性在服务器内部不起作用。CollectionTwo.find当内容发生CollectionOne变化时, Meteor 不会重新计算查询。

要实现您想要的,请手动管理发布,而不仅仅是返回光标。您需要observe在您的发布函数内部使用来观察 上的更改CollectionOne,然后手动调用this.set并将this.unset更改推送到客户端。发布文档中有一个这种技术的例子。该示例仅查看一个集合,但您可以将这个想法扩展到一组嵌套的观察。

我们将致力于糖,以使这种模式更容易实现。

于 2012-05-10T23:46:15.037 回答
4

在核心流星中有更好的模式之前,这两个大气包解决了这个问题:

https://atmosphere.meteor.com/package/server-deps

https://atmosphere.meteor.com/package/reactive-publish

使用陨石安装第二个包,使用“Meteor.reactivePublish”而不是“Meteor.publish”,当任何带有选项{“reactive”:true}的查询结果发生变化时,它将自动更新。

自述文件中的这个示例将准确发布用户团队可以看到的那些项目,并在用户更改团队或团队的可见项目更改时更新。

Meteor.reactivePublish(null, function() {
  if (this.userId) {
    var user = Meteor.users.findOne({_id: this.userId}, {reactive: true});
    if (user.team) {
      var team = Collections.teams.findOne({_id: user.team}, {reactive: true});
      var visibleItems = _.compact(team.visibleItems);
      return Collections.items.find({_id: {$in: visibleItems}});
    }
  }
});
于 2014-01-25T00:18:41.287 回答
0

您可以使用reactive-publish包(我是作者之一):

Meteor.publish "items", ->
  @autorun (computation) =>
    not_hidden = CollectionOne.find({}, {fields: my_id: 1}).fetch()
    CollectionTwo.find _id: $in: _.pluck not_hidden, 'my_id'

重要的是将查询的字段从 限制CollectionOne为 only my_id,否则autorun将在CollectionOne文档中的任何字段更改时重新运行,而不仅仅是my_id.

于 2015-10-03T12:08:46.500 回答