【问题标题】:How do I specify which Meteor Subscription should be used to render in React?如何指定应该使用哪个 Meteor Subscription 在 React 中渲染?
【发布时间】:2016-08-30 19:26:57
【问题描述】:

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

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

// 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();
  )
}

【问题讨论】:

  • 如果订阅了所有数据,那么所有数据都将在 minimongo 中可用。因此,可以在本地进行搜索。
  • 问题是 minimongo 目前不支持 $text,据我所知,解决这个问题的唯一方法是在服务器端进行 $text 搜索

标签: mongodb meteor reactjs


【解决方案1】:

在您的情况下,您实际上并不需要两个单独的订阅。只需将内容合并到一个订阅中,因此毫无疑问。例如:

// 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();

【讨论】:

  • 这很聪明。
  • 谢谢,这是一个非常优雅的解决方案
【解决方案2】:

无法指定来自不同订阅的数据到同一个集合。这是因为 Meteor 将来自后端集合的所有订阅的数据组合到前端的同一个 Minimongo 集合中——结束,不同订阅的数据没有区别。

不幸的是,对于您的情况,这意味着没有可靠的方法来被动地使用 Minimongo 目前不支持的 $text 运算符。我建议要么用在前端工作的$regex 运算符替换它,要么编写一个返回所有匹配文档的 ids 的 Meteor 方法,并在前端使用这个列表,如:

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

当你的搜索参数改变时,你必须重新调用这个方法,因为它不是响应式的。

【讨论】:

  • 我没有考虑过使用 $regex,将对此进行研究。谢谢!
猜你喜欢
  • 1970-01-01
  • 2018-07-02
  • 1970-01-01
  • 2017-10-29
  • 1970-01-01
  • 2017-07-23
  • 2016-08-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多