如何指定应该在React中使用哪个Meteor订阅进行渲染?

时间:2016-08-30 02:48:40

标签: mongodb meteor reactjs

我对同一个集合的不同视图有多个订阅和发布。其中一个视图用于返回Mongo Collection上的文本搜索,而其他视图返回整个集合。

我的问题是当我尝试在客户端上查看结果时,我不确定如何指定使用搜索结果订阅。目前,我的客户端视图显示的是整个集合,而不是受限制的搜索结果。如何指定应使用哪个订阅?或者我误解了pub / sub模型?可能我应该只使用一次订阅?任何意见都赞赏!

// Server side publication
Meteor.publish("search", function(searchValue){
  if (!searchValue) {
    console.log("there is no search value");
    return remoteData.find({});
  }

  console.log("there is a search value and it is " + searchValue);
  return remoteData.find({$text:{$search: searchValue}});
});

Meteor.publish("allData", function (){
  return remoteData.find();
});

// Client Side subscription
var searchSubscription =  Meteor.subscribe("search", searchQuery);
var allDataSubscription =  Meteor.subscribe("allData");

// inside React Component 
// this returns everything, so I think it's using the allDataSubscription
filteredData() {
  return (
    remoteData.find({}).fetch();
  )
}

2 个答案:

答案 0 :(得分:2)

在您的情况下,您确实不需要两个单独的订阅。只需将内容合并到一个订阅中,就不会有任何疑问。例如:

// Server
Meteor.publish('myData', function (searchValue) {
  const selector = {};
  if (searchValue) {
    selector.$text = {
      $search: searchValue,
    };
  }
  return remoteData.find(selector);
});

// Client
const myDataHandle =  Meteor.subscribe('myData', searchQuery);
...
remoteData.find({}).fetch();

答案 1 :(得分:1)

无法指定来自同一集合的不同订阅的数据。这是因为Meteor将来自后端集合的所有订阅的数据与前面的同一Minimongo集合相结合 - 结束,来自不同订阅的数据之间没有区别。

不幸的是,对于您的情况,这意味着没有可靠的方法来反应性使用Minimongo目前不支持的$text运算符。我建议将其替换为在前端工作的$regex运算符,或者编写一个返回所有匹配文档的ID的Meteor方法,并在前端使用此列表,如:

remoteData.find({ _id: { $in: matchingIds } }).fetch();

当您的搜索参数发生变化时,您必须重新调用此方法,因为它不是被动的。